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