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