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