]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/cstore_impl.rs
842335212eed60e216e3d364ae4c4590cecebedb
[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;
12 use encoder;
13 use schema;
14
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};
20 use rustc::hir::def;
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};
30
31 use std::any::Any;
32 use std::rc::Rc;
33
34 use syntax::ast;
35 use syntax::attr;
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;
42 use rustc::hir;
43
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
49                                         QueryConfig>::Value
50                 where T: IntoDefId,
51             {
52                 let $def_id = def_id_arg.into_def_id();
53                 assert!(!$def_id.is_local());
54
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);
57
58                 $tcx.dep_graph.read(dep_node);
59
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");
63                 $compute
64             })*
65
66             *providers = Providers {
67                 $($name,)*
68                 ..*providers
69             };
70         }
71     }
72 }
73
74 trait IntoDefId {
75     fn into_def_id(self) -> DefId;
76 }
77
78 impl IntoDefId for DefId {
79     fn into_def_id(self) -> DefId { self }
80 }
81
82 impl IntoDefId for CrateNum {
83     fn into_def_id(self) -> DefId { self.as_def_id() }
84 }
85
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) }
91     trait_def => {
92         tcx.alloc_trait_def(cdata.get_trait_def(def_id.index))
93     }
94     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
95     adt_destructor => {
96         let _ = cdata;
97         tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
98     }
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);
104         Rc::new(result)
105     }
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);
112         })
113     }
114     optimized_mir => {
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)
117         });
118
119         let mir = tcx.alloc_mir(mir);
120
121         mir
122     }
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)))
126     }
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)
149     }
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)
153     }
154     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
155
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 }
171         })
172     }
173     derive_registrar_fn => {
174         cdata.root.macro_derive_registrar.map(|index| {
175             DefId { krate: def_id.krate, index }
176         })
177     }
178 }
179
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");
184
185         if let Some(fn_like) = FnLikeNode::from_node(tcx.hir.get(node_id)) {
186             fn_like.constness() == hir::Constness::Const
187         } else {
188             false
189         }
190     }
191
192     *providers = Providers {
193         is_const_fn,
194         ..*providers
195     };
196 }
197
198 impl CrateStore for cstore::CStore {
199     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any> {
200         self.get_crate_data(krate)
201     }
202
203     fn metadata_loader(&self) -> &MetadataLoader {
204         &*self.metadata_loader
205     }
206
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)
210     }
211
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)
215     }
216
217     fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId>
218     {
219         let mut result = vec![];
220
221         self.iter_crate_data(|_, cdata| {
222             cdata.get_implementations_for_trait(filter, &self.dep_graph, &mut result)
223         });
224         result
225     }
226
227     fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem
228     {
229         self.read_dep_node(def);
230         self.get_crate_data(def.krate).get_associated_item(def.index)
231     }
232
233     fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool
234     {
235         self.do_is_statically_included_foreign_item(def_id)
236     }
237
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)
241         } else {
242             self.get_crate_data(def_id.krate)
243                 .is_dllimport_foreign_item(def_id.index, &self.dep_graph)
244         }
245     }
246
247     fn dep_kind(&self, cnum: CrateNum) -> DepKind
248     {
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);
252         data.dep_kind.get()
253     }
254
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);
258
259         self.dep_graph.read(dep_node);
260         if data.dep_kind.get() == DepKind::UnexportedMacrosOnly {
261             data.dep_kind.set(DepKind::MacrosOnly)
262         }
263     }
264
265     fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
266     {
267         self.get_crate_data(cnum).get_lang_items(&self.dep_graph)
268     }
269
270     fn missing_lang_items(&self, cnum: CrateNum)
271                           -> Vec<lang_items::LangItem>
272     {
273         self.get_crate_data(cnum).get_missing_lang_items(&self.dep_graph)
274     }
275
276     fn crate_name(&self, cnum: CrateNum) -> Symbol
277     {
278         self.get_crate_data(cnum).name
279     }
280
281     fn original_crate_name(&self, cnum: CrateNum) -> Symbol
282     {
283         self.get_crate_data(cnum).name()
284     }
285
286     fn crate_hash(&self, cnum: CrateNum) -> Svh
287     {
288         self.get_crate_hash(cnum)
289     }
290
291     fn crate_disambiguator(&self, cnum: CrateNum) -> Symbol
292     {
293         self.get_crate_data(cnum).disambiguator()
294     }
295
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.
304         //
305         // self.dep_graph.read(DepNode::MetaData(def));
306         self.get_crate_data(def.krate).def_key(def.index)
307     }
308
309     fn def_path(&self, def: DefId) -> DefPath {
310         // See `Note` above in `def_key()` for why this read is
311         // commented out:
312         //
313         // self.dep_graph.read(DepNode::MetaData(def));
314         self.get_crate_data(def.krate).def_path(def.index)
315     }
316
317     fn def_path_hash(&self, def: DefId) -> DefPathHash {
318         self.get_crate_data(def.krate).def_path_hash(def.index)
319     }
320
321     fn def_path_table(&self, cnum: CrateNum) -> Rc<DefPathTable> {
322         self.get_crate_data(cnum).def_path_table.clone()
323     }
324
325     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>
326     {
327         self.read_dep_node(def);
328         self.get_crate_data(def.krate).get_struct_field_names(def.index)
329     }
330
331     fn item_children(&self, def_id: DefId, sess: &Session) -> Vec<def::Export>
332     {
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);
337         result
338     }
339
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));
348         }
349
350         let (name, def) = data.get_macro(id.index);
351         let source_name = format!("<{} macros>", name);
352
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);
356
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);
361         }
362
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)));
367
368         LoadedMacro::MacroDef(ast::Item {
369             ident: ast::Ident::with_empty_ctxt(name),
370             id: ast::DUMMY_NODE_ID,
371             span: local_span,
372             attrs: attrs.iter().cloned().collect(),
373             node: ast::ItemKind::MacroDef(ast::MacroDef {
374                 tokens: body.into(),
375                 legacy: def.legacy,
376             }),
377             vis: ast::Visibility::Inherited,
378             tokens: None,
379         })
380     }
381
382     fn item_body<'a, 'tcx>(&self,
383                            tcx: TyCtxt<'a, 'tcx, 'tcx>,
384                            def_id: DefId)
385                            -> &'tcx hir::Body {
386         self.read_dep_node(def_id);
387
388         if let Some(cached) = tcx.hir.get_inlined_body_untracked(def_id) {
389             return cached;
390         }
391
392         debug!("item_body({:?}): inlining item", def_id);
393
394         self.get_crate_data(def_id.krate).item_body(tcx, def_id.index)
395     }
396
397     fn crates(&self) -> Vec<CrateNum>
398     {
399         let mut result = vec![];
400         self.iter_crate_data(|cnum, _| result.push(cnum));
401         result
402     }
403
404     fn used_libraries(&self) -> Vec<NativeLibrary>
405     {
406         self.get_used_libraries().borrow().clone()
407     }
408
409     fn used_link_args(&self) -> Vec<String>
410     {
411         self.get_used_link_args().borrow().clone()
412     }
413     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>
414     {
415         self.do_get_used_crates(prefer)
416     }
417
418     fn used_crate_source(&self, cnum: CrateNum) -> CrateSource
419     {
420         self.get_crate_data(cnum).source.clone()
421     }
422
423     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>
424     {
425         self.do_extern_mod_stmt_cnum(emod_id)
426     }
427
428     fn encode_metadata<'a, 'tcx>(&self,
429                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
430                                  link_meta: &LinkMeta,
431                                  reachable: &NodeSet)
432                                  -> (EncodedMetadata, EncodedMetadataHashes)
433     {
434         encoder::encode_metadata(tcx, link_meta, reachable)
435     }
436
437     fn metadata_encoding_version(&self) -> &[u8]
438     {
439         schema::METADATA_HEADER
440     }
441
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>> {
446         {
447             let visible_parent_map = self.visible_parent_map.borrow();
448             if !visible_parent_map.is_empty() {
449                 return visible_parent_map;
450             }
451         }
452
453         use std::collections::vec_deque::VecDeque;
454         use std::collections::hash_map::Entry;
455
456         let mut visible_parent_map = self.visible_parent_map.borrow_mut();
457
458         for cnum in (1 .. self.next_crate_num().as_usize()).map(CrateNum::new) {
459             let cdata = self.get_crate_data(cnum);
460
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,
464                 _ => {},
465             }
466
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();
470
471                 if self.visibility(child) != ty::Visibility::Public {
472                     return;
473                 }
474
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);
481                         }
482                     }
483                     Entry::Vacant(entry) => {
484                         entry.insert(parent);
485                         bfs_queue.push_back(child);
486                     }
487                 }
488             };
489
490             bfs_queue.push_back(DefId {
491                 krate: cnum,
492                 index: CRATE_DEF_INDEX
493             });
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);
497                 }
498             }
499         }
500
501         drop(visible_parent_map);
502         self.visible_parent_map.borrow()
503     }
504 }