]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/cstore_impl.rs
d0fa63a6163dbeb667d70afc69d8938b0c27cbec
[rust.git] / src / librustc_metadata / cstore_impl.rs
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.
4 //
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.
10
11 use cstore::{self, LoadedMacro};
12 use encoder;
13 use link_args;
14 use native_libs;
15 use foreign_modules;
16 use schema;
17
18 use rustc::ty::query::QueryConfig;
19 use rustc::middle::cstore::{CrateStore, DepKind,
20                             EncodedMetadata, NativeLibraryKind};
21 use rustc::middle::exported_symbols::ExportedSymbol;
22 use rustc::middle::stability::DeprecationEntry;
23 use rustc::hir::def;
24 use rustc::session::{CrateDisambiguator, Session};
25 use rustc::ty::{self, TyCtxt};
26 use rustc::ty::query::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::definitions::DefPathTable;
30 use rustc::util::nodemap::DefIdMap;
31 use rustc_data_structures::svh::Svh;
32
33 use std::any::Any;
34 use rustc_data_structures::sync::Lrc;
35 use std::sync::Arc;
36
37 use syntax::ast;
38 use syntax::attr;
39 use syntax::source_map;
40 use syntax::edition::Edition;
41 use syntax::parse::source_file_to_stream;
42 use syntax::symbol::Symbol;
43 use syntax_pos::{Span, NO_EXPANSION, FileName};
44 use rustc_data_structures::bit_set::BitSet;
45
46 macro_rules! provide {
47     (<$lt:tt> $tcx:ident, $def_id:ident, $other:ident, $cdata:ident,
48       $($name:ident => $compute:block)*) => {
49         pub fn provide_extern<$lt>(providers: &mut Providers<$lt>) {
50             $(fn $name<'a, $lt:$lt, T>($tcx: TyCtxt<'a, $lt, $lt>, def_id_arg: T)
51                                     -> <ty::queries::$name<$lt> as
52                                         QueryConfig<$lt>>::Value
53                 where T: IntoArgs,
54             {
55                 #[allow(unused_variables)]
56                 let ($def_id, $other) = def_id_arg.into_args();
57                 assert!(!$def_id.is_local());
58
59                 let def_path_hash = $tcx.def_path_hash(DefId {
60                     krate: $def_id.krate,
61                     index: CRATE_DEF_INDEX
62                 });
63                 let dep_node = def_path_hash
64                     .to_dep_node(::rustc::dep_graph::DepKind::CrateMetadata);
65                 // The DepNodeIndex of the DepNode::CrateMetadata should be
66                 // cached somewhere, so that we can use read_index().
67                 $tcx.dep_graph.read(dep_node);
68
69                 let $cdata = $tcx.crate_data_as_rc_any($def_id.krate);
70                 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
71                     .expect("CrateStore created data is not a CrateMetadata");
72                 $compute
73             })*
74
75             *providers = Providers {
76                 $($name,)*
77                 ..*providers
78             };
79         }
80     }
81 }
82
83 // small trait to work around different signature queries all being defined via
84 // the macro above.
85 trait IntoArgs {
86     fn into_args(self) -> (DefId, DefId);
87 }
88
89 impl IntoArgs for DefId {
90     fn into_args(self) -> (DefId, DefId) { (self, self) }
91 }
92
93 impl IntoArgs for CrateNum {
94     fn into_args(self) -> (DefId, DefId) { (self.as_def_id(), self.as_def_id()) }
95 }
96
97 impl IntoArgs for (CrateNum, DefId) {
98     fn into_args(self) -> (DefId, DefId) { (self.0.as_def_id(), self.1) }
99 }
100
101 provide! { <'tcx> tcx, def_id, other, cdata,
102     type_of => { cdata.get_type(def_id.index, tcx) }
103     generics_of => {
104         tcx.alloc_generics(cdata.get_generics(def_id.index, tcx.sess))
105     }
106     predicates_of => { Lrc::new(cdata.get_predicates(def_id.index, tcx)) }
107     predicates_defined_on => { Lrc::new(cdata.get_predicates_defined_on(def_id.index, tcx)) }
108     super_predicates_of => { Lrc::new(cdata.get_super_predicates(def_id.index, tcx)) }
109     trait_def => {
110         tcx.alloc_trait_def(cdata.get_trait_def(def_id.index, tcx.sess))
111     }
112     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
113     adt_destructor => {
114         let _ = cdata;
115         tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
116     }
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);
122         Lrc::new(result)
123     }
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);
130         })
131     }
132     optimized_mir => {
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)
135         });
136
137         let mir = tcx.alloc_mir(mir);
138
139         mir
140     }
141     mir_const_qualif => {
142         (cdata.mir_const_qualif(def_id.index), Lrc::new(BitSet::new_empty(0)))
143     }
144     fn_sig => { cdata.fn_sig(def_id.index, tcx) }
145     inherent_impls => { Lrc::new(cdata.get_inherent_implementations_for_type(def_id.index)) }
146     is_const_fn_raw => { cdata.is_const_fn_raw(def_id.index) }
147     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
148     describe_def => { cdata.get_def(def_id.index) }
149     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
150     lookup_stability => {
151         cdata.get_stability(def_id.index).map(|s| tcx.intern_stability(s))
152     }
153     lookup_deprecation_entry => {
154         cdata.get_deprecation(def_id.index).map(DeprecationEntry::external)
155     }
156     item_attrs => { cdata.get_item_attrs(def_id.index, tcx.sess) }
157     // FIXME(#38501) We've skipped a `read` on the `HirBody` of
158     // a `fn` when encoding, so the dep-tracking wouldn't work.
159     // This is only used by rustdoc anyway, which shouldn't have
160     // incremental recompilation ever enabled.
161     fn_arg_names => { cdata.get_fn_arg_names(def_id.index) }
162     rendered_const => { cdata.get_rendered_const(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     const_is_rvalue_promotable_to_static => {
166         cdata.const_is_rvalue_promotable_to_static(def_id.index)
167     }
168     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
169
170     dylib_dependency_formats => { Lrc::new(cdata.get_dylib_dependency_formats()) }
171     is_panic_runtime => { cdata.root.panic_runtime }
172     is_compiler_builtins => { cdata.root.compiler_builtins }
173     has_global_allocator => { cdata.root.has_global_allocator }
174     has_panic_handler => { cdata.root.has_panic_handler }
175     is_sanitizer_runtime => { cdata.root.sanitizer_runtime }
176     is_profiler_runtime => { cdata.root.profiler_runtime }
177     panic_strategy => { cdata.root.panic_strategy }
178     extern_crate => {
179         let r = Lrc::new(*cdata.extern_crate.lock());
180         r
181     }
182     is_no_builtins => { cdata.root.no_builtins }
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)
187             .iter()
188             .filter_map(|&(exported_symbol, export_level)| {
189                 if let ExportedSymbol::NonGeneric(def_id) = exported_symbol {
190                     return Some((def_id, export_level))
191                 } else {
192                     None
193                 }
194             })
195             .collect();
196
197         Lrc::new(reachable_non_generics)
198     }
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 }
204         })
205     }
206     proc_macro_decls_static => {
207         cdata.root.proc_macro_decls_static.map(|index| {
208             DefId { krate: def_id.krate, index }
209         })
210     }
211     crate_disambiguator => { cdata.root.disambiguator }
212     crate_hash => { cdata.root.hash }
213     original_crate_name => { cdata.root.name }
214
215     extra_filename => { cdata.root.extra_filename.clone() }
216
217
218     implementations_of_trait => {
219         let mut result = vec![];
220         let filter = Some(other);
221         cdata.get_implementations_for_trait(filter, &mut result);
222         Lrc::new(result)
223     }
224
225     all_trait_implementations => {
226         let mut result = vec![];
227         cdata.get_implementations_for_trait(None, &mut result);
228         Lrc::new(result)
229     }
230
231     visibility => { cdata.get_visibility(def_id.index) }
232     dep_kind => {
233         let r = *cdata.dep_kind.lock();
234         r
235     }
236     crate_name => { cdata.name }
237     item_children => {
238         let mut result = vec![];
239         cdata.each_child_of_item(def_id.index, |child| result.push(child), tcx.sess);
240         Lrc::new(result)
241     }
242     defined_lib_features => { Lrc::new(cdata.get_lib_features()) }
243     defined_lang_items => { Lrc::new(cdata.get_lang_items()) }
244     missing_lang_items => { Lrc::new(cdata.get_missing_lang_items()) }
245
246     missing_extern_crate_item => {
247         let r = match *cdata.extern_crate.borrow() {
248             Some(extern_crate) if !extern_crate.direct => true,
249             _ => false,
250         };
251         r
252     }
253
254     used_crate_source => { Lrc::new(cdata.source.clone()) }
255
256     exported_symbols => {
257         let cnum = cdata.cnum;
258         assert!(cnum != LOCAL_CRATE);
259
260         Arc::new(cdata.exported_symbols(tcx))
261     }
262 }
263
264 pub fn provide<'tcx>(providers: &mut Providers<'tcx>) {
265     // FIXME(#44234) - almost all of these queries have no sub-queries and
266     // therefore no actual inputs, they're just reading tables calculated in
267     // resolve! Does this work? Unsure! That's what the issue is about
268     *providers = Providers {
269         is_dllimport_foreign_item: |tcx, id| {
270             tcx.native_library_kind(id) == Some(NativeLibraryKind::NativeUnknown)
271         },
272         is_statically_included_foreign_item: |tcx, id| {
273             match tcx.native_library_kind(id) {
274                 Some(NativeLibraryKind::NativeStatic) |
275                 Some(NativeLibraryKind::NativeStaticNobundle) => true,
276                 _ => false,
277             }
278         },
279         native_library_kind: |tcx, id| {
280             tcx.native_libraries(id.krate)
281                 .iter()
282                 .filter(|lib| native_libs::relevant_lib(&tcx.sess, lib))
283                 .find(|lib| {
284                     let fm_id = match lib.foreign_module {
285                         Some(id) => id,
286                         None => return false,
287                     };
288                     tcx.foreign_modules(id.krate)
289                         .iter()
290                         .find(|m| m.def_id == fm_id)
291                         .expect("failed to find foreign module")
292                         .foreign_items
293                         .contains(&id)
294                 })
295                 .map(|l| l.kind)
296         },
297         native_libraries: |tcx, cnum| {
298             assert_eq!(cnum, LOCAL_CRATE);
299             Lrc::new(native_libs::collect(tcx))
300         },
301         foreign_modules: |tcx, cnum| {
302             assert_eq!(cnum, LOCAL_CRATE);
303             Lrc::new(foreign_modules::collect(tcx))
304         },
305         link_args: |tcx, cnum| {
306             assert_eq!(cnum, LOCAL_CRATE);
307             Lrc::new(link_args::collect(tcx))
308         },
309
310         // Returns a map from a sufficiently visible external item (i.e. an
311         // external item that is visible from at least one local module) to a
312         // sufficiently visible parent (considering modules that re-export the
313         // external item to be parents).
314         visible_parent_map: |tcx, cnum| {
315             use std::collections::vec_deque::VecDeque;
316             use std::collections::hash_map::Entry;
317
318             assert_eq!(cnum, LOCAL_CRATE);
319             let mut visible_parent_map: DefIdMap<DefId> = Default::default();
320
321             // Issue 46112: We want the map to prefer the shortest
322             // paths when reporting the path to an item. Therefore we
323             // build up the map via a breadth-first search (BFS),
324             // which naturally yields minimal-length paths.
325             //
326             // Note that it needs to be a BFS over the whole forest of
327             // crates, not just each individual crate; otherwise you
328             // only get paths that are locally minimal with respect to
329             // whatever crate we happened to encounter first in this
330             // traversal, but not globally minimal across all crates.
331             let bfs_queue = &mut VecDeque::new();
332
333             // Preferring shortest paths alone does not guarantee a
334             // deterministic result; so sort by crate num to avoid
335             // hashtable iteration non-determinism. This only makes
336             // things as deterministic as crate-nums assignment is,
337             // which is to say, its not deterministic in general. But
338             // we believe that libstd is consistently assigned crate
339             // num 1, so it should be enough to resolve #46112.
340             let mut crates: Vec<CrateNum> = (*tcx.crates()).clone();
341             crates.sort();
342
343             for &cnum in crates.iter() {
344                 // Ignore crates without a corresponding local `extern crate` item.
345                 if tcx.missing_extern_crate_item(cnum) {
346                     continue
347                 }
348
349                 bfs_queue.push_back(DefId {
350                     krate: cnum,
351                     index: CRATE_DEF_INDEX
352                 });
353             }
354
355             // (restrict scope of mutable-borrow of `visible_parent_map`)
356             {
357                 let visible_parent_map = &mut visible_parent_map;
358                 let mut add_child = |bfs_queue: &mut VecDeque<_>,
359                                      child: &def::Export,
360                                      parent: DefId| {
361                     if child.vis != ty::Visibility::Public {
362                         return;
363                     }
364
365                     let child = child.def.def_id();
366
367                     match visible_parent_map.entry(child) {
368                         Entry::Occupied(mut entry) => {
369                             // If `child` is defined in crate `cnum`, ensure
370                             // that it is mapped to a parent in `cnum`.
371                             if child.krate == cnum && entry.get().krate != cnum {
372                                 entry.insert(parent);
373                             }
374                         }
375                         Entry::Vacant(entry) => {
376                             entry.insert(parent);
377                             bfs_queue.push_back(child);
378                         }
379                     }
380                 };
381
382                 while let Some(def) = bfs_queue.pop_front() {
383                     for child in tcx.item_children(def).iter() {
384                         add_child(bfs_queue, child, def);
385                     }
386                 }
387             }
388
389             Lrc::new(visible_parent_map)
390         },
391
392         ..*providers
393     };
394 }
395
396 impl cstore::CStore {
397     pub fn export_macros_untracked(&self, cnum: CrateNum) {
398         let data = self.get_crate_data(cnum);
399         let mut dep_kind = data.dep_kind.lock();
400         if *dep_kind == DepKind::UnexportedMacrosOnly {
401             *dep_kind = DepKind::MacrosOnly;
402         }
403     }
404
405     pub fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind {
406         let data = self.get_crate_data(cnum);
407         let r = *data.dep_kind.lock();
408         r
409     }
410
411     pub fn crate_edition_untracked(&self, cnum: CrateNum) -> Edition {
412         self.get_crate_data(cnum).root.edition
413     }
414
415     pub fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
416         self.get_crate_data(def.krate).get_struct_field_names(def.index)
417     }
418
419     pub fn item_children_untracked(&self, def_id: DefId, sess: &Session) -> Vec<def::Export> {
420         let mut result = vec![];
421         self.get_crate_data(def_id.krate)
422             .each_child_of_item(def_id.index, |child| result.push(child), sess);
423         result
424     }
425
426     pub fn load_macro_untracked(&self, id: DefId, sess: &Session) -> LoadedMacro {
427         let data = self.get_crate_data(id.krate);
428         if let Some(ref proc_macros) = data.proc_macros {
429             return LoadedMacro::ProcMacro(proc_macros[id.index.to_proc_macro_index()].1.clone());
430         } else if data.name == "proc_macro" && data.item_name(id.index) == "quote" {
431             use syntax::ext::base::SyntaxExtension;
432             use syntax_ext::proc_macro_impl::BangProcMacro;
433
434             let client = ::proc_macro::bridge::client::Client::expand1(::proc_macro::quote);
435             let ext = SyntaxExtension::ProcMacro {
436                 expander: Box::new(BangProcMacro { client }),
437                 allow_internal_unstable: true,
438                 edition: data.root.edition,
439             };
440             return LoadedMacro::ProcMacro(Lrc::new(ext));
441         }
442
443         let def = data.get_macro(id.index);
444         let macro_full_name = data.def_path(id.index).to_string_friendly(|_| data.imported_name);
445         let source_name = FileName::Macros(macro_full_name);
446
447         let source_file = sess.parse_sess.source_map().new_source_file(source_name, def.body);
448         let local_span = Span::new(source_file.start_pos, source_file.end_pos, NO_EXPANSION);
449         let body = source_file_to_stream(&sess.parse_sess, source_file, None);
450
451         // Mark the attrs as used
452         let attrs = data.get_item_attrs(id.index, sess);
453         for attr in attrs.iter() {
454             attr::mark_used(attr);
455         }
456
457         let name = data.def_key(id.index).disambiguated_data.data
458             .get_opt_name().expect("no name in load_macro");
459         sess.imported_macro_spans.borrow_mut()
460             .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
461
462         LoadedMacro::MacroDef(ast::Item {
463             ident: ast::Ident::from_str(&name.as_str()),
464             id: ast::DUMMY_NODE_ID,
465             span: local_span,
466             attrs: attrs.iter().cloned().collect(),
467             node: ast::ItemKind::MacroDef(ast::MacroDef {
468                 tokens: body.into(),
469                 legacy: def.legacy,
470             }),
471             vis: source_map::respan(local_span.shrink_to_lo(), ast::VisibilityKind::Inherited),
472             tokens: None,
473         })
474     }
475
476     pub fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem {
477         self.get_crate_data(def.krate).get_associated_item(def.index)
478     }
479 }
480
481 impl CrateStore for cstore::CStore {
482     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any> {
483         self.get_crate_data(krate)
484     }
485
486     fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics {
487         self.get_crate_data(def.krate).get_generics(def.index, sess)
488     }
489
490     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol
491     {
492         self.get_crate_data(cnum).name
493     }
494
495     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator
496     {
497         self.get_crate_data(cnum).root.disambiguator
498     }
499
500     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh
501     {
502         self.get_crate_data(cnum).root.hash
503     }
504
505     /// Returns the `DefKey` for a given `DefId`. This indicates the
506     /// parent `DefId` as well as some idea of what kind of data the
507     /// `DefId` refers to.
508     fn def_key(&self, def: DefId) -> DefKey {
509         // Note: loading the def-key (or def-path) for a def-id is not
510         // a *read* of its metadata. This is because the def-id is
511         // really just an interned shorthand for a def-path, which is the
512         // canonical name for an item.
513         //
514         // self.dep_graph.read(DepNode::MetaData(def));
515         self.get_crate_data(def.krate).def_key(def.index)
516     }
517
518     fn def_path(&self, def: DefId) -> DefPath {
519         // See `Note` above in `def_key()` for why this read is
520         // commented out:
521         //
522         // self.dep_graph.read(DepNode::MetaData(def));
523         self.get_crate_data(def.krate).def_path(def.index)
524     }
525
526     fn def_path_hash(&self, def: DefId) -> DefPathHash {
527         self.get_crate_data(def.krate).def_path_hash(def.index)
528     }
529
530     fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
531         self.get_crate_data(cnum).def_path_table.clone()
532     }
533
534     fn crates_untracked(&self) -> Vec<CrateNum>
535     {
536         let mut result = vec![];
537         self.iter_crate_data(|cnum, _| result.push(cnum));
538         result
539     }
540
541     fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>
542     {
543         self.do_extern_mod_stmt_cnum(emod_id)
544     }
545
546     fn postorder_cnums_untracked(&self) -> Vec<CrateNum> {
547         self.do_postorder_cnums_untracked()
548     }
549
550     fn encode_metadata<'a, 'tcx>(&self,
551                                  tcx: TyCtxt<'a, 'tcx, 'tcx>)
552                                  -> EncodedMetadata
553     {
554         encoder::encode_metadata(tcx)
555     }
556
557     fn metadata_encoding_version(&self) -> &[u8]
558     {
559         schema::METADATA_HEADER
560     }
561 }