]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/cstore_impl.rs
Auto merge of #41853 - Keruspe:install, r=alexcrichton
[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::dep_graph::DepTrackingMapConfig;
16 use rustc::middle::cstore::{CrateStore, CrateSource, LibSource, DepKind,
17                             ExternCrate, NativeLibrary, MetadataLoader, LinkMeta,
18                             LinkagePreference, LoadedMacro, EncodedMetadata};
19 use rustc::hir::def;
20 use rustc::middle::lang_items;
21 use rustc::session::Session;
22 use rustc::ty::{self, TyCtxt};
23 use rustc::ty::maps::Providers;
24 use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
25
26 use rustc::dep_graph::{DepNode, GlobalMetaDataKind};
27 use rustc::hir::map::{DefKey, DefPath, DisambiguatedDefPathData};
28 use rustc::util::nodemap::{NodeSet, DefIdMap};
29 use rustc_back::PanicStrategy;
30
31 use std::any::Any;
32 use std::rc::Rc;
33
34 use syntax::ast;
35 use syntax::attr;
36 use syntax::parse::filemap_to_stream;
37 use syntax::symbol::Symbol;
38 use syntax_pos::{Span, NO_EXPANSION};
39 use rustc::hir::svh::Svh;
40 use rustc::hir;
41
42 macro_rules! provide {
43     (<$lt:tt> $tcx:ident, $def_id:ident, $cdata:ident $($name:ident => $compute:block)*) => {
44         pub fn provide<$lt>(providers: &mut Providers<$lt>) {
45             $(fn $name<'a, $lt:$lt>($tcx: TyCtxt<'a, $lt, $lt>, $def_id: DefId)
46                                     -> <ty::queries::$name<$lt> as
47                                         DepTrackingMapConfig>::Value {
48                 assert!(!$def_id.is_local());
49
50                 $tcx.dep_graph.read(DepNode::MetaData($def_id));
51
52                 let $cdata = $tcx.sess.cstore.crate_data_as_rc_any($def_id.krate);
53                 let $cdata = $cdata.downcast_ref::<cstore::CrateMetadata>()
54                     .expect("CrateStore crated ata is not a CrateMetadata");
55                 $compute
56             })*
57
58             *providers = Providers {
59                 $($name,)*
60                 ..*providers
61             };
62         }
63     }
64 }
65
66 provide! { <'tcx> tcx, def_id, cdata
67     type_of => { cdata.get_type(def_id.index, tcx) }
68     generics_of => { tcx.alloc_generics(cdata.get_generics(def_id.index)) }
69     predicates_of => { cdata.get_predicates(def_id.index, tcx) }
70     super_predicates_of => { cdata.get_super_predicates(def_id.index, tcx) }
71     trait_def => {
72         tcx.alloc_trait_def(cdata.get_trait_def(def_id.index))
73     }
74     adt_def => { cdata.get_adt_def(def_id.index, tcx) }
75     adt_destructor => {
76         let _ = cdata;
77         tcx.calculate_dtor(def_id, &mut |_,_| Ok(()))
78     }
79     variances_of => { Rc::new(cdata.get_item_variances(def_id.index)) }
80     associated_item_def_ids => {
81         let mut result = vec![];
82         cdata.each_child_of_item(def_id.index, |child| result.push(child.def.def_id()));
83         Rc::new(result)
84     }
85     associated_item => { cdata.get_associated_item(def_id.index) }
86     impl_trait_ref => { cdata.get_impl_trait(def_id.index, tcx) }
87     impl_polarity => { cdata.get_impl_polarity(def_id.index) }
88     coerce_unsized_info => {
89         cdata.get_coerce_unsized_info(def_id.index).unwrap_or_else(|| {
90             bug!("coerce_unsized_info: `{:?}` is missing its info", def_id);
91         })
92     }
93     optimized_mir => {
94         let mir = cdata.maybe_get_optimized_mir(tcx, def_id.index).unwrap_or_else(|| {
95             bug!("get_optimized_mir: missing MIR for `{:?}`", def_id)
96         });
97
98         let mir = tcx.alloc_mir(mir);
99
100         mir
101     }
102     mir_const_qualif => { cdata.mir_const_qualif(def_id.index) }
103     typeck_tables_of => { cdata.item_body_tables(def_id.index, tcx) }
104     closure_kind => { cdata.closure_kind(def_id.index) }
105     closure_type => { cdata.closure_ty(def_id.index, tcx) }
106     inherent_impls => { Rc::new(cdata.get_inherent_implementations_for_type(def_id.index)) }
107     is_foreign_item => { cdata.is_foreign_item(def_id.index) }
108     describe_def => { cdata.get_def(def_id.index) }
109     def_span => { cdata.get_span(def_id.index, &tcx.sess) }
110     stability => { cdata.get_stability(def_id.index) }
111     deprecation => { cdata.get_deprecation(def_id.index) }
112     item_attrs => { cdata.get_item_attrs(def_id.index, &tcx.dep_graph) }
113     // FIXME(#38501) We've skipped a `read` on the `HirBody` of
114     // a `fn` when encoding, so the dep-tracking wouldn't work.
115     // This is only used by rustdoc anyway, which shouldn't have
116     // incremental recompilation ever enabled.
117     fn_arg_names => { cdata.get_fn_arg_names(def_id.index) }
118     impl_parent => { cdata.get_parent_impl(def_id.index) }
119     trait_of_item => { cdata.get_trait_of_item(def_id.index) }
120     is_exported_symbol => {
121         let dep_node = cdata.metadata_dep_node(GlobalMetaDataKind::ExportedSymbols);
122         cdata.exported_symbols.get(&tcx.dep_graph, dep_node).contains(&def_id.index)
123     }
124     item_body_nested_bodies => { Rc::new(cdata.item_body_nested_bodies(def_id.index)) }
125     const_is_rvalue_promotable_to_static => {
126         cdata.const_is_rvalue_promotable_to_static(def_id.index)
127     }
128     is_mir_available => { cdata.is_item_mir_available(def_id.index) }
129 }
130
131 impl CrateStore for cstore::CStore {
132     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any> {
133         self.get_crate_data(krate)
134     }
135
136     fn metadata_loader(&self) -> &MetadataLoader {
137         &*self.metadata_loader
138     }
139
140     fn visibility(&self, def: DefId) -> ty::Visibility {
141         self.dep_graph.read(DepNode::MetaData(def));
142         self.get_crate_data(def.krate).get_visibility(def.index)
143     }
144
145     fn item_generics_cloned(&self, def: DefId) -> ty::Generics {
146         self.dep_graph.read(DepNode::MetaData(def));
147         self.get_crate_data(def.krate).get_generics(def.index)
148     }
149
150     fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId>
151     {
152         if let Some(def_id) = filter {
153             self.dep_graph.read(DepNode::MetaData(def_id));
154         }
155         let mut result = vec![];
156         self.iter_crate_data(|_, cdata| {
157             cdata.get_implementations_for_trait(filter, &self.dep_graph, &mut result)
158         });
159         result
160     }
161
162     fn impl_defaultness(&self, def: DefId) -> hir::Defaultness
163     {
164         self.dep_graph.read(DepNode::MetaData(def));
165         self.get_crate_data(def.krate).get_impl_defaultness(def.index)
166     }
167
168     fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem
169     {
170         self.dep_graph.read(DepNode::MetaData(def));
171         self.get_crate_data(def.krate).get_associated_item(def.index)
172     }
173
174     fn is_const_fn(&self, did: DefId) -> bool
175     {
176         self.dep_graph.read(DepNode::MetaData(did));
177         self.get_crate_data(did.krate).is_const_fn(did.index)
178     }
179
180     fn is_default_impl(&self, impl_did: DefId) -> bool {
181         self.dep_graph.read(DepNode::MetaData(impl_did));
182         self.get_crate_data(impl_did.krate).is_default_impl(impl_did.index)
183     }
184
185     fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool
186     {
187         self.do_is_statically_included_foreign_item(def_id)
188     }
189
190     fn is_dllimport_foreign_item(&self, def_id: DefId) -> bool {
191         if def_id.krate == LOCAL_CRATE {
192             self.dllimport_foreign_items.borrow().contains(&def_id.index)
193         } else {
194             self.get_crate_data(def_id.krate)
195                 .is_dllimport_foreign_item(def_id.index, &self.dep_graph)
196         }
197     }
198
199     fn dylib_dependency_formats(&self, cnum: CrateNum)
200                                 -> Vec<(CrateNum, LinkagePreference)>
201     {
202         self.get_crate_data(cnum).get_dylib_dependency_formats(&self.dep_graph)
203     }
204
205     fn dep_kind(&self, cnum: CrateNum) -> DepKind
206     {
207         let data = self.get_crate_data(cnum);
208         let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
209         self.dep_graph.read(dep_node);
210         data.dep_kind.get()
211     }
212
213     fn export_macros(&self, cnum: CrateNum) {
214         let data = self.get_crate_data(cnum);
215         let dep_node = data.metadata_dep_node(GlobalMetaDataKind::CrateDeps);
216
217         self.dep_graph.read(dep_node);
218         if data.dep_kind.get() == DepKind::UnexportedMacrosOnly {
219             data.dep_kind.set(DepKind::MacrosOnly)
220         }
221     }
222
223     fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
224     {
225         self.get_crate_data(cnum).get_lang_items(&self.dep_graph)
226     }
227
228     fn missing_lang_items(&self, cnum: CrateNum)
229                           -> Vec<lang_items::LangItem>
230     {
231         self.get_crate_data(cnum).get_missing_lang_items(&self.dep_graph)
232     }
233
234     fn is_allocator(&self, cnum: CrateNum) -> bool
235     {
236         self.get_crate_data(cnum).is_allocator(&self.dep_graph)
237     }
238
239     fn is_panic_runtime(&self, cnum: CrateNum) -> bool
240     {
241         self.get_crate_data(cnum).is_panic_runtime(&self.dep_graph)
242     }
243
244     fn is_compiler_builtins(&self, cnum: CrateNum) -> bool {
245         self.get_crate_data(cnum).is_compiler_builtins(&self.dep_graph)
246     }
247
248     fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool {
249         self.get_crate_data(cnum).is_sanitizer_runtime(&self.dep_graph)
250     }
251
252     fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy {
253         self.get_crate_data(cnum).panic_strategy(&self.dep_graph)
254     }
255
256     fn crate_name(&self, cnum: CrateNum) -> Symbol
257     {
258         self.get_crate_data(cnum).name
259     }
260
261     fn original_crate_name(&self, cnum: CrateNum) -> Symbol
262     {
263         self.get_crate_data(cnum).name()
264     }
265
266     fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate>
267     {
268         self.get_crate_data(cnum).extern_crate.get()
269     }
270
271     fn crate_hash(&self, cnum: CrateNum) -> Svh
272     {
273         self.get_crate_hash(cnum)
274     }
275
276     fn crate_disambiguator(&self, cnum: CrateNum) -> Symbol
277     {
278         self.get_crate_data(cnum).disambiguator()
279     }
280
281     fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
282     {
283         self.get_crate_data(cnum).root.plugin_registrar_fn.map(|index| DefId {
284             krate: cnum,
285             index: index
286         })
287     }
288
289     fn derive_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
290     {
291         self.get_crate_data(cnum).root.macro_derive_registrar.map(|index| DefId {
292             krate: cnum,
293             index: index
294         })
295     }
296
297     fn native_libraries(&self, cnum: CrateNum) -> Vec<NativeLibrary>
298     {
299         self.get_crate_data(cnum).get_native_libraries(&self.dep_graph)
300     }
301
302     fn exported_symbols(&self, cnum: CrateNum) -> Vec<DefId>
303     {
304         self.get_crate_data(cnum).get_exported_symbols(&self.dep_graph)
305     }
306
307     fn is_no_builtins(&self, cnum: CrateNum) -> bool {
308         self.get_crate_data(cnum).is_no_builtins(&self.dep_graph)
309     }
310
311     fn retrace_path(&self,
312                     cnum: CrateNum,
313                     path: &[DisambiguatedDefPathData])
314                     -> Option<DefId> {
315         let cdata = self.get_crate_data(cnum);
316         cdata.def_path_table
317              .retrace_path(&path)
318              .map(|index| DefId { krate: cnum, index: index })
319     }
320
321     /// Returns the `DefKey` for a given `DefId`. This indicates the
322     /// parent `DefId` as well as some idea of what kind of data the
323     /// `DefId` refers to.
324     fn def_key(&self, def: DefId) -> DefKey {
325         // Note: loading the def-key (or def-path) for a def-id is not
326         // a *read* of its metadata. This is because the def-id is
327         // really just an interned shorthand for a def-path, which is the
328         // canonical name for an item.
329         //
330         // self.dep_graph.read(DepNode::MetaData(def));
331         self.get_crate_data(def.krate).def_key(def.index)
332     }
333
334     fn def_path(&self, def: DefId) -> DefPath {
335         // See `Note` above in `def_key()` for why this read is
336         // commented out:
337         //
338         // self.dep_graph.read(DepNode::MetaData(def));
339         self.get_crate_data(def.krate).def_path(def.index)
340     }
341
342     fn def_path_hash(&self, def: DefId) -> u64 {
343         self.get_crate_data(def.krate).def_path_hash(def.index)
344     }
345
346     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>
347     {
348         self.dep_graph.read(DepNode::MetaData(def));
349         self.get_crate_data(def.krate).get_struct_field_names(def.index)
350     }
351
352     fn item_children(&self, def_id: DefId) -> Vec<def::Export>
353     {
354         self.dep_graph.read(DepNode::MetaData(def_id));
355         let mut result = vec![];
356         self.get_crate_data(def_id.krate)
357             .each_child_of_item(def_id.index, |child| result.push(child));
358         result
359     }
360
361     fn load_macro(&self, id: DefId, sess: &Session) -> LoadedMacro {
362         let data = self.get_crate_data(id.krate);
363         if let Some(ref proc_macros) = data.proc_macros {
364             return LoadedMacro::ProcMacro(proc_macros[id.index.as_usize() - 1].1.clone());
365         }
366
367         let (name, def) = data.get_macro(id.index);
368         let source_name = format!("<{} macros>", name);
369
370         let filemap = sess.parse_sess.codemap().new_filemap(source_name, def.body);
371         let local_span = Span { lo: filemap.start_pos, hi: filemap.end_pos, ctxt: NO_EXPANSION };
372         let body = filemap_to_stream(&sess.parse_sess, filemap);
373
374         // Mark the attrs as used
375         let attrs = data.get_item_attrs(id.index, &self.dep_graph);
376         for attr in attrs.iter() {
377             attr::mark_used(attr);
378         }
379
380         let name = data.def_key(id.index).disambiguated_data.data
381             .get_opt_name().expect("no name in load_macro");
382         sess.imported_macro_spans.borrow_mut()
383             .insert(local_span, (name.to_string(), data.get_span(id.index, sess)));
384
385         LoadedMacro::MacroDef(ast::Item {
386             ident: ast::Ident::with_empty_ctxt(name),
387             id: ast::DUMMY_NODE_ID,
388             span: local_span,
389             attrs: attrs.iter().cloned().collect(),
390             node: ast::ItemKind::MacroDef(body.into()),
391             vis: ast::Visibility::Inherited,
392         })
393     }
394
395     fn item_body<'a, 'tcx>(&self,
396                            tcx: TyCtxt<'a, 'tcx, 'tcx>,
397                            def_id: DefId)
398                            -> &'tcx hir::Body {
399         if let Some(cached) = tcx.hir.get_inlined_body(def_id) {
400             return cached;
401         }
402
403         self.dep_graph.read(DepNode::MetaData(def_id));
404         debug!("item_body({}): inlining item", tcx.item_path_str(def_id));
405
406         self.get_crate_data(def_id.krate).item_body(tcx, def_id.index)
407     }
408
409     fn crates(&self) -> Vec<CrateNum>
410     {
411         let mut result = vec![];
412         self.iter_crate_data(|cnum, _| result.push(cnum));
413         result
414     }
415
416     fn used_libraries(&self) -> Vec<NativeLibrary>
417     {
418         self.get_used_libraries().borrow().clone()
419     }
420
421     fn used_link_args(&self) -> Vec<String>
422     {
423         self.get_used_link_args().borrow().clone()
424     }
425     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>
426     {
427         self.do_get_used_crates(prefer)
428     }
429
430     fn used_crate_source(&self, cnum: CrateNum) -> CrateSource
431     {
432         self.get_crate_data(cnum).source.clone()
433     }
434
435     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>
436     {
437         self.do_extern_mod_stmt_cnum(emod_id)
438     }
439
440     fn encode_metadata<'a, 'tcx>(&self,
441                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
442                                  link_meta: &LinkMeta,
443                                  reachable: &NodeSet)
444                                  -> EncodedMetadata
445     {
446         encoder::encode_metadata(tcx, link_meta, reachable)
447     }
448
449     fn metadata_encoding_version(&self) -> &[u8]
450     {
451         schema::METADATA_HEADER
452     }
453
454     /// Returns a map from a sufficiently visible external item (i.e. an external item that is
455     /// visible from at least one local module) to a sufficiently visible parent (considering
456     /// modules that re-export the external item to be parents).
457     fn visible_parent_map<'a>(&'a self) -> ::std::cell::Ref<'a, DefIdMap<DefId>> {
458         {
459             let visible_parent_map = self.visible_parent_map.borrow();
460             if !visible_parent_map.is_empty() {
461                 return visible_parent_map;
462             }
463         }
464
465         use std::collections::vec_deque::VecDeque;
466         use std::collections::hash_map::Entry;
467
468         let mut visible_parent_map = self.visible_parent_map.borrow_mut();
469
470         for cnum in (1 .. self.next_crate_num().as_usize()).map(CrateNum::new) {
471             let cdata = self.get_crate_data(cnum);
472
473             match cdata.extern_crate.get() {
474                 // Ignore crates without a corresponding local `extern crate` item.
475                 Some(extern_crate) if !extern_crate.direct => continue,
476                 _ => {},
477             }
478
479             let mut bfs_queue = &mut VecDeque::new();
480             let mut add_child = |bfs_queue: &mut VecDeque<_>, child: def::Export, parent: DefId| {
481                 let child = child.def.def_id();
482
483                 if self.visibility(child) != ty::Visibility::Public {
484                     return;
485                 }
486
487                 match visible_parent_map.entry(child) {
488                     Entry::Occupied(mut entry) => {
489                         // If `child` is defined in crate `cnum`, ensure
490                         // that it is mapped to a parent in `cnum`.
491                         if child.krate == cnum && entry.get().krate != cnum {
492                             entry.insert(parent);
493                         }
494                     }
495                     Entry::Vacant(entry) => {
496                         entry.insert(parent);
497                         bfs_queue.push_back(child);
498                     }
499                 }
500             };
501
502             bfs_queue.push_back(DefId {
503                 krate: cnum,
504                 index: CRATE_DEF_INDEX
505             });
506             while let Some(def) = bfs_queue.pop_front() {
507                 for child in self.item_children(def) {
508                     add_child(bfs_queue, child, def);
509                 }
510             }
511         }
512
513         drop(visible_parent_map);
514         self.visible_parent_map.borrow()
515     }
516 }