]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/cstore_impl.rs
e08f0f2c752dfaf057ef871bbaec80935883a775
[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     crate_disambiguator => { cdata.disambiguator() }
179     crate_hash => { cdata.hash() }
180     original_crate_name => { cdata.name() }
181 }
182
183 pub fn provide_local<'tcx>(providers: &mut Providers<'tcx>) {
184     fn is_const_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
185         let node_id = tcx.hir.as_local_node_id(def_id)
186                              .expect("Non-local call to local provider is_const_fn");
187
188         if let Some(fn_like) = FnLikeNode::from_node(tcx.hir.get(node_id)) {
189             fn_like.constness() == hir::Constness::Const
190         } else {
191             false
192         }
193     }
194
195     *providers = Providers {
196         is_const_fn,
197         ..*providers
198     };
199 }
200
201 impl CrateStore for cstore::CStore {
202     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any> {
203         self.get_crate_data(krate)
204     }
205
206     fn metadata_loader(&self) -> &MetadataLoader {
207         &*self.metadata_loader
208     }
209
210     fn visibility(&self, def: DefId) -> ty::Visibility {
211         self.read_dep_node(def);
212         self.get_crate_data(def.krate).get_visibility(def.index)
213     }
214
215     fn item_generics_cloned(&self, def: DefId) -> ty::Generics {
216         self.read_dep_node(def);
217         self.get_crate_data(def.krate).get_generics(def.index)
218     }
219
220     fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId>
221     {
222         let mut result = vec![];
223
224         self.iter_crate_data(|_, cdata| {
225             cdata.get_implementations_for_trait(filter, &self.dep_graph, &mut result)
226         });
227         result
228     }
229
230     fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem
231     {
232         self.read_dep_node(def);
233         self.get_crate_data(def.krate).get_associated_item(def.index)
234     }
235
236     fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool
237     {
238         self.do_is_statically_included_foreign_item(def_id)
239     }
240
241     fn is_dllimport_foreign_item(&self, def_id: DefId) -> bool {
242         if def_id.krate == LOCAL_CRATE {
243             self.dllimport_foreign_items.borrow().contains(&def_id.index)
244         } else {
245             self.get_crate_data(def_id.krate)
246                 .is_dllimport_foreign_item(def_id.index, &self.dep_graph)
247         }
248     }
249
250     fn dep_kind(&self, cnum: CrateNum) -> DepKind
251     {
252         let data = self.get_crate_data(cnum);
253         let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
254         self.dep_graph.read(dep_node);
255         data.dep_kind.get()
256     }
257
258     fn export_macros(&self, cnum: CrateNum) {
259         let data = self.get_crate_data(cnum);
260         let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
261
262         self.dep_graph.read(dep_node);
263         if data.dep_kind.get() == DepKind::UnexportedMacrosOnly {
264             data.dep_kind.set(DepKind::MacrosOnly)
265         }
266     }
267
268     fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
269     {
270         self.get_crate_data(cnum).get_lang_items(&self.dep_graph)
271     }
272
273     fn missing_lang_items(&self, cnum: CrateNum)
274                           -> Vec<lang_items::LangItem>
275     {
276         self.get_crate_data(cnum).get_missing_lang_items(&self.dep_graph)
277     }
278
279     fn crate_name(&self, cnum: CrateNum) -> Symbol
280     {
281         self.get_crate_data(cnum).name
282     }
283
284     /// Returns the `DefKey` for a given `DefId`. This indicates the
285     /// parent `DefId` as well as some idea of what kind of data the
286     /// `DefId` refers to.
287     fn def_key(&self, def: DefId) -> DefKey {
288         // Note: loading the def-key (or def-path) for a def-id is not
289         // a *read* of its metadata. This is because the def-id is
290         // really just an interned shorthand for a def-path, which is the
291         // canonical name for an item.
292         //
293         // self.dep_graph.read(DepNode::MetaData(def));
294         self.get_crate_data(def.krate).def_key(def.index)
295     }
296
297     fn def_path(&self, def: DefId) -> DefPath {
298         // See `Note` above in `def_key()` for why this read is
299         // commented out:
300         //
301         // self.dep_graph.read(DepNode::MetaData(def));
302         self.get_crate_data(def.krate).def_path(def.index)
303     }
304
305     fn def_path_hash(&self, def: DefId) -> DefPathHash {
306         self.get_crate_data(def.krate).def_path_hash(def.index)
307     }
308
309     fn def_path_table(&self, cnum: CrateNum) -> Rc<DefPathTable> {
310         self.get_crate_data(cnum).def_path_table.clone()
311     }
312
313     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>
314     {
315         self.read_dep_node(def);
316         self.get_crate_data(def.krate).get_struct_field_names(def.index)
317     }
318
319     fn item_children(&self, def_id: DefId, sess: &Session) -> Vec<def::Export>
320     {
321         self.read_dep_node(def_id);
322         let mut result = vec![];
323         self.get_crate_data(def_id.krate)
324             .each_child_of_item(def_id.index, |child| result.push(child), sess);
325         result
326     }
327
328     fn load_macro(&self, id: DefId, sess: &Session) -> LoadedMacro {
329         let data = self.get_crate_data(id.krate);
330         if let Some(ref proc_macros) = data.proc_macros {
331             return LoadedMacro::ProcMacro(proc_macros[id.index.as_usize() - 1].1.clone());
332         } else if data.name == "proc_macro" &&
333                   self.get_crate_data(id.krate).item_name(id.index) == "quote" {
334             let ext = SyntaxExtension::ProcMacro(Box::new(::proc_macro::__internal::Quoter));
335             return LoadedMacro::ProcMacro(Rc::new(ext));
336         }
337
338         let (name, def) = data.get_macro(id.index);
339         let source_name = format!("<{} macros>", name);
340
341         let filemap = sess.parse_sess.codemap().new_filemap(source_name, def.body);
342         let local_span = Span::new(filemap.start_pos, filemap.end_pos, NO_EXPANSION);
343         let body = filemap_to_stream(&sess.parse_sess, filemap, None);
344
345         // Mark the attrs as used
346         let attrs = data.get_item_attrs(id.index, &self.dep_graph);
347         for attr in attrs.iter() {
348             attr::mark_used(attr);
349         }
350
351         let name = data.def_key(id.index).disambiguated_data.data
352             .get_opt_name().expect("no name in load_macro");
353         sess.imported_macro_spans.borrow_mut()
354             .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
355
356         LoadedMacro::MacroDef(ast::Item {
357             ident: ast::Ident::with_empty_ctxt(name),
358             id: ast::DUMMY_NODE_ID,
359             span: local_span,
360             attrs: attrs.iter().cloned().collect(),
361             node: ast::ItemKind::MacroDef(ast::MacroDef {
362                 tokens: body.into(),
363                 legacy: def.legacy,
364             }),
365             vis: ast::Visibility::Inherited,
366             tokens: None,
367         })
368     }
369
370     fn item_body<'a, 'tcx>(&self,
371                            tcx: TyCtxt<'a, 'tcx, 'tcx>,
372                            def_id: DefId)
373                            -> &'tcx hir::Body {
374         self.read_dep_node(def_id);
375
376         if let Some(cached) = tcx.hir.get_inlined_body_untracked(def_id) {
377             return cached;
378         }
379
380         debug!("item_body({:?}): inlining item", def_id);
381
382         self.get_crate_data(def_id.krate).item_body(tcx, def_id.index)
383     }
384
385     fn crates(&self) -> Vec<CrateNum>
386     {
387         let mut result = vec![];
388         self.iter_crate_data(|cnum, _| result.push(cnum));
389         result
390     }
391
392     fn used_libraries(&self) -> Vec<NativeLibrary>
393     {
394         self.get_used_libraries().borrow().clone()
395     }
396
397     fn used_link_args(&self) -> Vec<String>
398     {
399         self.get_used_link_args().borrow().clone()
400     }
401     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>
402     {
403         self.do_get_used_crates(prefer)
404     }
405
406     fn used_crate_source(&self, cnum: CrateNum) -> CrateSource
407     {
408         self.get_crate_data(cnum).source.clone()
409     }
410
411     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>
412     {
413         self.do_extern_mod_stmt_cnum(emod_id)
414     }
415
416     fn encode_metadata<'a, 'tcx>(&self,
417                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
418                                  link_meta: &LinkMeta,
419                                  reachable: &NodeSet)
420                                  -> (EncodedMetadata, EncodedMetadataHashes)
421     {
422         encoder::encode_metadata(tcx, link_meta, reachable)
423     }
424
425     fn metadata_encoding_version(&self) -> &[u8]
426     {
427         schema::METADATA_HEADER
428     }
429
430     /// Returns a map from a sufficiently visible external item (i.e. an external item that is
431     /// visible from at least one local module) to a sufficiently visible parent (considering
432     /// modules that re-export the external item to be parents).
433     fn visible_parent_map<'a>(&'a self, sess: &Session) -> ::std::cell::Ref<'a, DefIdMap<DefId>> {
434         {
435             let visible_parent_map = self.visible_parent_map.borrow();
436             if !visible_parent_map.is_empty() {
437                 return visible_parent_map;
438             }
439         }
440
441         use std::collections::vec_deque::VecDeque;
442         use std::collections::hash_map::Entry;
443
444         let mut visible_parent_map = self.visible_parent_map.borrow_mut();
445
446         for cnum in (1 .. self.next_crate_num().as_usize()).map(CrateNum::new) {
447             let cdata = self.get_crate_data(cnum);
448
449             match cdata.extern_crate.get() {
450                 // Ignore crates without a corresponding local `extern crate` item.
451                 Some(extern_crate) if !extern_crate.direct => continue,
452                 _ => {},
453             }
454
455             let bfs_queue = &mut VecDeque::new();
456             let mut add_child = |bfs_queue: &mut VecDeque<_>, child: def::Export, parent: DefId| {
457                 let child = child.def.def_id();
458
459                 if self.visibility(child) != ty::Visibility::Public {
460                     return;
461                 }
462
463                 match visible_parent_map.entry(child) {
464                     Entry::Occupied(mut entry) => {
465                         // If `child` is defined in crate `cnum`, ensure
466                         // that it is mapped to a parent in `cnum`.
467                         if child.krate == cnum && entry.get().krate != cnum {
468                             entry.insert(parent);
469                         }
470                     }
471                     Entry::Vacant(entry) => {
472                         entry.insert(parent);
473                         bfs_queue.push_back(child);
474                     }
475                 }
476             };
477
478             bfs_queue.push_back(DefId {
479                 krate: cnum,
480                 index: CRATE_DEF_INDEX
481             });
482             while let Some(def) = bfs_queue.pop_front() {
483                 for child in self.item_children(def, sess) {
484                     add_child(bfs_queue, child, def);
485                 }
486             }
487         }
488
489         drop(visible_parent_map);
490         self.visible_parent_map.borrow()
491     }
492 }