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