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