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