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.
18 use rustc::ty::maps::QueryConfig;
19 use rustc::middle::cstore::{CrateStore, DepKind,
20 MetadataLoader, LinkMeta,
21 LoadedMacro, EncodedMetadata, NativeLibraryKind};
22 use rustc::middle::exported_symbols::ExportedSymbol;
23 use rustc::middle::stability::DeprecationEntry;
25 use rustc::session::{CrateDisambiguator, Session};
26 use rustc::ty::{self, TyCtxt};
27 use rustc::ty::maps::Providers;
28 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE, CRATE_DEF_INDEX};
29 use rustc::hir::map::{DefKey, DefPath, DefPathHash};
30 use rustc::hir::map::blocks::FnLikeNode;
31 use rustc::hir::map::definitions::DefPathTable;
32 use rustc::util::nodemap::DefIdMap;
35 use rustc_data_structures::sync::Lrc;
41 use syntax::ext::base::SyntaxExtension;
42 use syntax::parse::filemap_to_stream;
43 use syntax::symbol::Symbol;
44 use syntax_pos::{Span, NO_EXPANSION, FileName};
45 use rustc_data_structures::indexed_set::IdxSetBuf;
48 macro_rules! provide {
49 (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
50 $($name:ident => $compute:block)*) => {
51 pub fn provide_extern<$lt>(providers: &mut Providers<$lt>) {
52 $(fn $name<'a, $lt:$lt, T>($tcx: TyCtxt<'a, $lt, $lt>, def_id_arg: T)
53 -> <ty::queries::$name<$lt> as
57 #[allow(unused_variables)]
58 let ($def_id, $other) = def_id_arg.into_args();
59 assert!(!$def_id.is_local());
61 let def_path_hash = $tcx.def_path_hash(DefId {
63 index: CRATE_DEF_INDEX
65 let dep_node = def_path_hash
66 .to_dep_node(::rustc::dep_graph::DepKind::CrateMetadata);
67 // The DepNodeIndex of the DepNode::CrateMetadata should be
68 // cached somewhere, so that we can use read_index().
69 $tcx.dep_graph.read(dep_node);
71 let $cdata = $tcx.crate_data_as_rc_any($def_id.krate);
72 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
73 .expect("CrateStore crated ata is not a CrateMetadata");
77 *providers = Providers {
85 // small trait to work around different signature queries all being defined via
88 fn into_args(self) -> (DefId, DefId);
91 impl IntoArgs for DefId {
92 fn into_args(self) -> (DefId, DefId) { (self, self) }
95 impl IntoArgs for CrateNum {
96 fn into_args(self) -> (DefId, DefId) { (self.as_def_id(), self.as_def_id()) }
99 impl IntoArgs for (CrateNum, DefId) {
100 fn into_args(self) -> (DefId, DefId) { (self.0.as_def_id(), self.1) }
103 provide! { <'tcx> tcx, def_id, other, cdata,
104 type_of => { cdata.get_type(def_id.index, tcx) }
106 tcx.alloc_generics(cdata.get_generics(def_id.index, tcx.sess))
108 predicates_of => { cdata.get_predicates(def_id.index, tcx) }
109 super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
111 tcx.alloc_trait_def(cdata.get_trait_def(def_id.index, tcx.sess))
113 adt_def => { cdata.get_adt_def(def_id.index, tcx) }
116 tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
118 variances_of => { Lrc::new(cdata.get_item_variances(def_id.index)) }
119 associated_item_def_ids => {
120 let mut result = vec![];
121 cdata.each_child_of_item(def_id.index,
122 |child| result.push(child.def.def_id()), tcx.sess);
125 associated_item => { cdata.get_associated_item(def_id.index) }
126 impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
127 impl_polarity => { cdata.get_impl_polarity(def_id.index) }
128 coerce_unsized_info => {
129 cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
130 bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
134 let mir = cdata.maybe_get_optimized_mir(tcx, def_id.index).unwrap_or_else(|| {
135 bug!("get_optimized_mir: missing MIR for `{:?}`", def_id)
138 let mir = tcx.alloc_mir(mir);
142 mir_const_qualif => {
143 (cdata.mir_const_qualif(def_id.index), Lrc::new(IdxSetBuf::new_empty(0)))
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 rendered_const => { cdata.get_rendered_const(def_id.index) }
164 impl_parent => { cdata.get_parent_impl(def_id.index) }
165 trait_of_item => { cdata.get_trait_of_item(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() }
179 let r = Lrc::new(*cdata.extern_crate.lock());
182 is_no_builtins => { cdata.is_no_builtins(tcx.sess) }
183 impl_defaultness => { cdata.get_impl_defaultness(def_id.index) }
184 reachable_non_generics => {
185 let reachable_non_generics = tcx
186 .exported_symbols(cdata.cnum)
188 .filter_map(|&(exported_symbol, export_level)| {
189 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
190 return Some((def_id, export_level))
197 Lrc::new(reachable_non_generics)
199 native_libraries => { Lrc::new(cdata.get_native_libraries(tcx.sess)) }
200 foreign_modules => { Lrc::new(cdata.get_foreign_modules(tcx.sess)) }
201 plugin_registrar_fn => {
202 cdata.root.plugin_registrar_fn.map(|index| {
203 DefId { krate: def_id.krate, index }
206 derive_registrar_fn => {
207 cdata.root.macro_derive_registrar.map(|index| {
208 DefId { krate: def_id.krate, index }
211 crate_disambiguator => { cdata.disambiguator() }
212 crate_hash => { cdata.hash() }
213 original_crate_name => { cdata.name() }
215 extra_filename => { cdata.root.extra_filename.clone() }
218 implementations_of_trait => {
219 let mut result = vec![];
220 let filter = Some(other);
221 cdata.get_implementations_for_trait(filter, &mut result);
225 all_trait_implementations => {
226 let mut result = vec![];
227 cdata.get_implementations_for_trait(None, &mut result);
231 visibility => { cdata.get_visibility(def_id.index) }
233 let r = *cdata.dep_kind.lock();
236 crate_name => { cdata.name }
238 let mut result = vec![];
239 cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
242 defined_lang_items => { Lrc::new(cdata.get_lang_items()) }
243 missing_lang_items => { Lrc::new(cdata.get_missing_lang_items()) }
245 missing_extern_crate_item => {
246 let r = match *cdata.extern_crate.borrow() {
247 Some(extern_crate) if !extern_crate.direct => true,
253 used_crate_source => { Lrc::new(cdata.source.clone()) }
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(tcx))
268 wasm_custom_sections => { Lrc::new(cdata.wasm_custom_sections()) }
271 pub fn provide<'tcx>(providers: &mut Providers<'tcx>) {
272 fn is_const_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
273 let node_id = tcx.hir.as_local_node_id(def_id)
274 .expect("Non-local call to local provider is_const_fn");
276 if let Some(fn_like) = FnLikeNode::from_node(tcx.hir.get(node_id)) {
277 fn_like.constness() == hir::Constness::Const
283 // FIXME(#44234) - almost all of these queries have no sub-queries and
284 // therefore no actual inputs, they're just reading tables calculated in
285 // resolve! Does this work? Unsure! That's what the issue is about
286 *providers = Providers {
288 is_dllimport_foreign_item: |tcx, id| {
289 tcx.native_library_kind(id) == Some(NativeLibraryKind::NativeUnknown)
291 is_statically_included_foreign_item: |tcx, id| {
292 match tcx.native_library_kind(id) {
293 Some(NativeLibraryKind::NativeStatic) |
294 Some(NativeLibraryKind::NativeStaticNobundle) => true,
298 native_library_kind: |tcx, id| {
299 tcx.native_libraries(id.krate)
301 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
303 let fm_id = match lib.foreign_module {
305 None => return false,
307 tcx.foreign_modules(id.krate)
309 .find(|m| m.def_id == fm_id)
310 .expect("failed to find foreign module")
316 native_libraries: |tcx, cnum| {
317 assert_eq!(cnum, LOCAL_CRATE);
318 Lrc::new(native_libs::collect(tcx))
320 foreign_modules: |tcx, cnum| {
321 assert_eq!(cnum, LOCAL_CRATE);
322 Lrc::new(foreign_modules::collect(tcx))
324 link_args: |tcx, cnum| {
325 assert_eq!(cnum, LOCAL_CRATE);
326 Lrc::new(link_args::collect(tcx))
329 // Returns a map from a sufficiently visible external item (i.e. an
330 // external item that is visible from at least one local module) to a
331 // sufficiently visible parent (considering modules that re-export the
332 // external item to be parents).
333 visible_parent_map: |tcx, cnum| {
334 use std::collections::vec_deque::VecDeque;
335 use std::collections::hash_map::Entry;
337 assert_eq!(cnum, LOCAL_CRATE);
338 let mut visible_parent_map: DefIdMap<DefId> = DefIdMap();
340 // Issue 46112: We want the map to prefer the shortest
341 // paths when reporting the path to an item. Therefore we
342 // build up the map via a breadth-first search (BFS),
343 // which naturally yields minimal-length paths.
345 // Note that it needs to be a BFS over the whole forest of
346 // crates, not just each individual crate; otherwise you
347 // only get paths that are locally minimal with respect to
348 // whatever crate we happened to encounter first in this
349 // traversal, but not globally minimal across all crates.
350 let bfs_queue = &mut VecDeque::new();
352 // Preferring shortest paths alone does not guarantee a
353 // deterministic result; so sort by crate num to avoid
354 // hashtable iteration non-determinism. This only makes
355 // things as deterministic as crate-nums assignment is,
356 // which is to say, its not deterministic in general. But
357 // we believe that libstd is consistently assigned crate
358 // num 1, so it should be enough to resolve #46112.
359 let mut crates: Vec<CrateNum> = (*tcx.crates()).clone();
362 for &cnum in crates.iter() {
363 // Ignore crates without a corresponding local `extern crate` item.
364 if tcx.missing_extern_crate_item(cnum) {
368 bfs_queue.push_back(DefId {
370 index: CRATE_DEF_INDEX
374 // (restrict scope of mutable-borrow of `visible_parent_map`)
376 let visible_parent_map = &mut visible_parent_map;
377 let mut add_child = |bfs_queue: &mut VecDeque<_>,
380 if child.vis != ty::Visibility::Public {
384 let child = child.def.def_id();
386 match visible_parent_map.entry(child) {
387 Entry::Occupied(mut entry) => {
388 // If `child` is defined in crate `cnum`, ensure
389 // that it is mapped to a parent in `cnum`.
390 if child.krate == cnum && entry.get().krate != cnum {
391 entry.insert(parent);
394 Entry::Vacant(entry) => {
395 entry.insert(parent);
396 bfs_queue.push_back(child);
401 while let Some(def) = bfs_queue.pop_front() {
402 for child in tcx.item_children(def).iter() {
403 add_child(bfs_queue, child, def);
408 Lrc::new(visible_parent_map)
415 impl CrateStore for cstore::CStore {
416 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<Any> {
417 self.get_crate_data(krate)
420 fn metadata_loader(&self) -> &MetadataLoader {
421 &*self.metadata_loader
424 fn visibility_untracked(&self, def: DefId) -> ty::Visibility {
425 self.get_crate_data(def.krate).get_visibility(def.index)
428 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics {
429 self.get_crate_data(def.krate).get_generics(def.index, sess)
432 fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem
434 self.get_crate_data(def.krate).get_associated_item(def.index)
437 fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind
439 let data = self.get_crate_data(cnum);
440 let r = *data.dep_kind.lock();
444 fn export_macros_untracked(&self, cnum: CrateNum) {
445 let data = self.get_crate_data(cnum);
446 let mut dep_kind = data.dep_kind.lock();
447 if *dep_kind == DepKind::UnexportedMacrosOnly {
448 *dep_kind = DepKind::MacrosOnly;
452 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol
454 self.get_crate_data(cnum).name
457 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator
459 self.get_crate_data(cnum).disambiguator()
462 fn crate_hash_untracked(&self, cnum: CrateNum) -> hir::svh::Svh
464 self.get_crate_data(cnum).hash()
467 /// Returns the `DefKey` for a given `DefId`. This indicates the
468 /// parent `DefId` as well as some idea of what kind of data the
469 /// `DefId` refers to.
470 fn def_key(&self, def: DefId) -> DefKey {
471 // Note: loading the def-key (or def-path) for a def-id is not
472 // a *read* of its metadata. This is because the def-id is
473 // really just an interned shorthand for a def-path, which is the
474 // canonical name for an item.
476 // self.dep_graph.read(DepNode::MetaData(def));
477 self.get_crate_data(def.krate).def_key(def.index)
480 fn def_path(&self, def: DefId) -> DefPath {
481 // See `Note` above in `def_key()` for why this read is
484 // self.dep_graph.read(DepNode::MetaData(def));
485 self.get_crate_data(def.krate).def_path(def.index)
488 fn def_path_hash(&self, def: DefId) -> DefPathHash {
489 self.get_crate_data(def.krate).def_path_hash(def.index)
492 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
493 self.get_crate_data(cnum).def_path_table.clone()
496 fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name>
498 self.get_crate_data(def.krate).get_struct_field_names(def.index)
501 fn item_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<def::Export>
503 let mut result = vec![];
504 self.get_crate_data(def_id.krate)
505 .each_child_of_item(def_id.index, |child| result.push(child), sess);
509 fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
510 let data = self.get_crate_data(id.krate);
511 if let Some(ref proc_macros) = data.proc_macros {
512 return LoadedMacro::ProcMacro(proc_macros[id.index.to_proc_macro_index()].1.clone());
513 } else if data.name == "proc_macro" &&
514 self.get_crate_data(id.krate).item_name(id.index) == "quote" {
515 let ext = SyntaxExtension::ProcMacro(Box::new(::proc_macro::__internal::Quoter));
516 return LoadedMacro::ProcMacro(Lrc::new(ext));
519 let (name, def) = data.get_macro(id.index);
520 let source_name = FileName::Macros(name.to_string());
522 let filemap = sess.parse_sess.codemap().new_filemap(source_name, def.body);
523 let local_span = Span::new(filemap.start_pos, filemap.end_pos, NO_EXPANSION);
524 let body = filemap_to_stream(&sess.parse_sess, filemap, None);
526 // Mark the attrs as used
527 let attrs = data.get_item_attrs(id.index, sess);
528 for attr in attrs.iter() {
529 attr::mark_used(attr);
532 let name = data.def_key(id.index).disambiguated_data.data
533 .get_opt_name().expect("no name in load_macro");
534 sess.imported_macro_spans.borrow_mut()
535 .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
537 LoadedMacro::MacroDef(ast::Item {
538 ident: ast::Ident::from_str(&name),
539 id: ast::DUMMY_NODE_ID,
541 attrs: attrs.iter().cloned().collect(),
542 node: ast::ItemKind::MacroDef(ast::MacroDef {
546 vis: codemap::respan(local_span.shrink_to_lo(), ast::VisibilityKind::Inherited),
551 fn crates_untracked(&self) -> Vec<CrateNum>
553 let mut result = vec![];
554 self.iter_crate_data(|cnum, _| result.push(cnum));
558 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>
560 self.do_extern_mod_stmt_cnum(emod_id)
563 fn postorder_cnums_untracked(&self) -> Vec<CrateNum> {
564 self.do_postorder_cnums_untracked()
567 fn encode_metadata<'a, 'tcx>(&self,
568 tcx: TyCtxt<'a, 'tcx, 'tcx>,
569 link_meta: &LinkMeta)
572 encoder::encode_metadata(tcx, link_meta)
575 fn metadata_encoding_version(&self) -> &[u8]
577 schema::METADATA_HEADER