]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/cstore.rs
Rollup merge of #41141 - michaelwoerister:direct-metadata-ich-final, r=nikomatsakis
[rust.git] / src / librustc / middle / cstore.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 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
12 // file at the top-level directory of this distribution and at
13 // http://rust-lang.org/COPYRIGHT.
14 //
15 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
16 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
17 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
18 // option. This file may not be copied, modified, or distributed
19 // except according to those terms.
20
21 // the rustc crate store interface. This also includes types that
22 // are *mostly* used as a part of that interface, but these should
23 // probably get a better home if someone can find one.
24
25 use hir::def::{self, Def};
26 use hir::def_id::{CrateNum, DefId, DefIndex};
27 use hir::map as hir_map;
28 use hir::map::definitions::{Definitions, DefKey, DisambiguatedDefPathData};
29 use hir::svh::Svh;
30 use ich;
31 use middle::lang_items;
32 use ty::{self, TyCtxt};
33 use session::Session;
34 use session::search_paths::PathKind;
35 use util::nodemap::{NodeSet, DefIdMap};
36
37 use std::any::Any;
38 use std::collections::BTreeMap;
39 use std::path::PathBuf;
40 use std::rc::Rc;
41 use syntax::ast;
42 use syntax::attr;
43 use syntax::ext::base::SyntaxExtension;
44 use syntax::symbol::Symbol;
45 use syntax_pos::Span;
46 use rustc_back::target::Target;
47 use hir;
48 use rustc_back::PanicStrategy;
49
50 pub use self::NativeLibraryKind::*;
51
52 // lonely orphan structs and enums looking for a better home
53
54 #[derive(Clone, Debug)]
55 pub struct LinkMeta {
56     pub crate_name: Symbol,
57     pub crate_hash: Svh,
58 }
59
60 // Where a crate came from on the local filesystem. One of these three options
61 // must be non-None.
62 #[derive(PartialEq, Clone, Debug)]
63 pub struct CrateSource {
64     pub dylib: Option<(PathBuf, PathKind)>,
65     pub rlib: Option<(PathBuf, PathKind)>,
66     pub rmeta: Option<(PathBuf, PathKind)>,
67 }
68
69 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
70 pub enum DepKind {
71     /// A dependency that is only used for its macros, none of which are visible from other crates.
72     /// These are included in the metadata only as placeholders and are ignored when decoding.
73     UnexportedMacrosOnly,
74     /// A dependency that is only used for its macros.
75     MacrosOnly,
76     /// A dependency that is always injected into the dependency list and so
77     /// doesn't need to be linked to an rlib, e.g. the injected allocator.
78     Implicit,
79     /// A dependency that is required by an rlib version of this crate.
80     /// Ordinary `extern crate`s result in `Explicit` dependencies.
81     Explicit,
82 }
83
84 impl DepKind {
85     pub fn macros_only(self) -> bool {
86         match self {
87             DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true,
88             DepKind::Implicit | DepKind::Explicit => false,
89         }
90     }
91 }
92
93 #[derive(PartialEq, Clone, Debug)]
94 pub enum LibSource {
95     Some(PathBuf),
96     MetadataOnly,
97     None,
98 }
99
100 impl LibSource {
101     pub fn is_some(&self) -> bool {
102         if let LibSource::Some(_) = *self {
103             true
104         } else {
105             false
106         }
107     }
108
109     pub fn option(&self) -> Option<PathBuf> {
110         match *self {
111             LibSource::Some(ref p) => Some(p.clone()),
112             LibSource::MetadataOnly | LibSource::None => None,
113         }
114     }
115 }
116
117 #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
118 pub enum LinkagePreference {
119     RequireDynamic,
120     RequireStatic,
121 }
122
123 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
124 pub enum NativeLibraryKind {
125     NativeStatic,    // native static library (.a archive)
126     NativeStaticNobundle, // native static library, which doesn't get bundled into .rlibs
127     NativeFramework, // macOS-specific
128     NativeUnknown,   // default way to specify a dynamic library
129 }
130
131 #[derive(Clone, Hash, RustcEncodable, RustcDecodable)]
132 pub struct NativeLibrary {
133     pub kind: NativeLibraryKind,
134     pub name: Symbol,
135     pub cfg: Option<ast::MetaItem>,
136     pub foreign_items: Vec<DefIndex>,
137 }
138
139 pub enum LoadedMacro {
140     MacroDef(ast::Item),
141     ProcMacro(Rc<SyntaxExtension>),
142 }
143
144 #[derive(Copy, Clone, Debug)]
145 pub struct ExternCrate {
146     /// def_id of an `extern crate` in the current crate that caused
147     /// this crate to be loaded; note that there could be multiple
148     /// such ids
149     pub def_id: DefId,
150
151     /// span of the extern crate that caused this to be loaded
152     pub span: Span,
153
154     /// If true, then this crate is the crate named by the extern
155     /// crate referenced above. If false, then this crate is a dep
156     /// of the crate.
157     pub direct: bool,
158
159     /// Number of links to reach the extern crate `def_id`
160     /// declaration; used to select the extern crate with the shortest
161     /// path
162     pub path_len: usize,
163 }
164
165 pub struct EncodedMetadata {
166     pub raw_data: Vec<u8>,
167     pub hashes: Vec<EncodedMetadataHash>,
168 }
169
170 /// The hash for some metadata that (when saving) will be exported
171 /// from this crate, or which (when importing) was exported by an
172 /// upstream crate.
173 #[derive(Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
174 pub struct EncodedMetadataHash {
175     pub def_index: DefIndex,
176     pub hash: ich::Fingerprint,
177 }
178
179 /// A store of Rust crates, through with their metadata
180 /// can be accessed.
181 pub trait CrateStore {
182     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any>;
183
184     // item info
185     fn describe_def(&self, def: DefId) -> Option<Def>;
186     fn def_span(&self, sess: &Session, def: DefId) -> Span;
187     fn stability(&self, def: DefId) -> Option<attr::Stability>;
188     fn deprecation(&self, def: DefId) -> Option<attr::Deprecation>;
189     fn visibility(&self, def: DefId) -> ty::Visibility;
190     fn visible_parent_map<'a>(&'a self) -> ::std::cell::Ref<'a, DefIdMap<DefId>>;
191     fn item_generics_cloned(&self, def: DefId) -> ty::Generics;
192     fn item_attrs(&self, def_id: DefId) -> Vec<ast::Attribute>;
193     fn fn_arg_names(&self, did: DefId) -> Vec<ast::Name>;
194
195     // trait info
196     fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId>;
197
198     // impl info
199     fn impl_polarity(&self, def: DefId) -> hir::ImplPolarity;
200     fn impl_parent(&self, impl_def_id: DefId) -> Option<DefId>;
201
202     // trait/impl-item info
203     fn trait_of_item(&self, def_id: DefId) -> Option<DefId>;
204     fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem;
205
206     // flags
207     fn is_const_fn(&self, did: DefId) -> bool;
208     fn is_default_impl(&self, impl_did: DefId) -> bool;
209     fn is_foreign_item(&self, did: DefId) -> bool;
210     fn is_dllimport_foreign_item(&self, def: DefId) -> bool;
211     fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool;
212     fn is_exported_symbol(&self, def_id: DefId) -> bool;
213
214     // crate metadata
215     fn dylib_dependency_formats(&self, cnum: CrateNum)
216                                     -> Vec<(CrateNum, LinkagePreference)>;
217     fn dep_kind(&self, cnum: CrateNum) -> DepKind;
218     fn export_macros(&self, cnum: CrateNum);
219     fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>;
220     fn missing_lang_items(&self, cnum: CrateNum) -> Vec<lang_items::LangItem>;
221     fn is_staged_api(&self, cnum: CrateNum) -> bool;
222     fn is_allocator(&self, cnum: CrateNum) -> bool;
223     fn is_panic_runtime(&self, cnum: CrateNum) -> bool;
224     fn is_compiler_builtins(&self, cnum: CrateNum) -> bool;
225     fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool;
226     fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy;
227     fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate>;
228     /// The name of the crate as it is referred to in source code of the current
229     /// crate.
230     fn crate_name(&self, cnum: CrateNum) -> Symbol;
231     /// The name of the crate as it is stored in the crate's metadata.
232     fn original_crate_name(&self, cnum: CrateNum) -> Symbol;
233     fn crate_hash(&self, cnum: CrateNum) -> Svh;
234     fn crate_disambiguator(&self, cnum: CrateNum) -> Symbol;
235     fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>;
236     fn derive_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>;
237     fn native_libraries(&self, cnum: CrateNum) -> Vec<NativeLibrary>;
238     fn exported_symbols(&self, cnum: CrateNum) -> Vec<DefId>;
239     fn is_no_builtins(&self, cnum: CrateNum) -> bool;
240
241     // resolve
242     fn retrace_path(&self,
243                     cnum: CrateNum,
244                     path_data: &[DisambiguatedDefPathData])
245                     -> Option<DefId>;
246     fn def_key(&self, def: DefId) -> DefKey;
247     fn def_path(&self, def: DefId) -> hir_map::DefPath;
248     fn def_path_hash(&self, def: DefId) -> u64;
249     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>;
250     fn item_children(&self, did: DefId) -> Vec<def::Export>;
251     fn load_macro(&self, did: DefId, sess: &Session) -> LoadedMacro;
252
253     // misc. metadata
254     fn maybe_get_item_body<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, def: DefId)
255                                      -> Option<&'tcx hir::Body>;
256     fn item_body_nested_bodies(&self, def: DefId) -> BTreeMap<hir::BodyId, hir::Body>;
257     fn const_is_rvalue_promotable_to_static(&self, def: DefId) -> bool;
258
259     fn is_item_mir_available(&self, def: DefId) -> bool;
260
261     // This is basically a 1-based range of ints, which is a little
262     // silly - I may fix that.
263     fn crates(&self) -> Vec<CrateNum>;
264     fn used_libraries(&self) -> Vec<NativeLibrary>;
265     fn used_link_args(&self) -> Vec<String>;
266
267     // utility functions
268     fn metadata_filename(&self) -> &str;
269     fn metadata_section_name(&self, target: &Target) -> &str;
270     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>;
271     fn used_crate_source(&self, cnum: CrateNum) -> CrateSource;
272     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
273     fn encode_metadata<'a, 'tcx>(&self,
274                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
275                                  link_meta: &LinkMeta,
276                                  reachable: &NodeSet)
277                                  -> EncodedMetadata;
278     fn metadata_encoding_version(&self) -> &[u8];
279 }
280
281 // FIXME: find a better place for this?
282 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
283     let mut err_count = 0;
284     {
285         let mut say = |s: &str| {
286             match (sp, sess) {
287                 (_, None) => bug!("{}", s),
288                 (Some(sp), Some(sess)) => sess.span_err(sp, s),
289                 (None, Some(sess)) => sess.err(s),
290             }
291             err_count += 1;
292         };
293         if s.is_empty() {
294             say("crate name must not be empty");
295         }
296         for c in s.chars() {
297             if c.is_alphanumeric() { continue }
298             if c == '_'  { continue }
299             say(&format!("invalid character `{}` in crate name: `{}`", c, s));
300         }
301     }
302
303     if err_count > 0 {
304         sess.unwrap().abort_if_errors();
305     }
306 }
307
308 /// A dummy crate store that does not support any non-local crates,
309 /// for test purposes.
310 pub struct DummyCrateStore;
311
312 #[allow(unused_variables)]
313 impl CrateStore for DummyCrateStore {
314     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any>
315         { bug!("crate_data_as_rc_any") }
316     // item info
317     fn describe_def(&self, def: DefId) -> Option<Def> { bug!("describe_def") }
318     fn def_span(&self, sess: &Session, def: DefId) -> Span { bug!("def_span") }
319     fn stability(&self, def: DefId) -> Option<attr::Stability> { bug!("stability") }
320     fn deprecation(&self, def: DefId) -> Option<attr::Deprecation> { bug!("deprecation") }
321     fn visibility(&self, def: DefId) -> ty::Visibility { bug!("visibility") }
322     fn visible_parent_map<'a>(&'a self) -> ::std::cell::Ref<'a, DefIdMap<DefId>> {
323         bug!("visible_parent_map")
324     }
325     fn item_generics_cloned(&self, def: DefId) -> ty::Generics
326         { bug!("item_generics_cloned") }
327     fn item_attrs(&self, def_id: DefId) -> Vec<ast::Attribute> { bug!("item_attrs") }
328     fn fn_arg_names(&self, did: DefId) -> Vec<ast::Name> { bug!("fn_arg_names") }
329
330     // trait info
331     fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId> { vec![] }
332
333     // impl info
334     fn impl_polarity(&self, def: DefId) -> hir::ImplPolarity { bug!("impl_polarity") }
335     fn impl_parent(&self, def: DefId) -> Option<DefId> { bug!("impl_parent") }
336
337     // trait/impl-item info
338     fn trait_of_item(&self, def_id: DefId) -> Option<DefId> { bug!("trait_of_item") }
339     fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem
340         { bug!("associated_item_cloned") }
341
342     // flags
343     fn is_const_fn(&self, did: DefId) -> bool { bug!("is_const_fn") }
344     fn is_default_impl(&self, impl_did: DefId) -> bool { bug!("is_default_impl") }
345     fn is_foreign_item(&self, did: DefId) -> bool { bug!("is_foreign_item") }
346     fn is_dllimport_foreign_item(&self, id: DefId) -> bool { false }
347     fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool { false }
348     fn is_exported_symbol(&self, def_id: DefId) -> bool { false }
349
350     // crate metadata
351     fn dylib_dependency_formats(&self, cnum: CrateNum)
352                                     -> Vec<(CrateNum, LinkagePreference)>
353         { bug!("dylib_dependency_formats") }
354     fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
355         { bug!("lang_items") }
356     fn missing_lang_items(&self, cnum: CrateNum) -> Vec<lang_items::LangItem>
357         { bug!("missing_lang_items") }
358     fn is_staged_api(&self, cnum: CrateNum) -> bool { bug!("is_staged_api") }
359     fn dep_kind(&self, cnum: CrateNum) -> DepKind { bug!("is_explicitly_linked") }
360     fn export_macros(&self, cnum: CrateNum) { bug!("export_macros") }
361     fn is_allocator(&self, cnum: CrateNum) -> bool { bug!("is_allocator") }
362     fn is_panic_runtime(&self, cnum: CrateNum) -> bool { bug!("is_panic_runtime") }
363     fn is_compiler_builtins(&self, cnum: CrateNum) -> bool { bug!("is_compiler_builtins") }
364     fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool { bug!("is_sanitizer_runtime") }
365     fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy {
366         bug!("panic_strategy")
367     }
368     fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate> { bug!("extern_crate") }
369     fn crate_name(&self, cnum: CrateNum) -> Symbol { bug!("crate_name") }
370     fn original_crate_name(&self, cnum: CrateNum) -> Symbol {
371         bug!("original_crate_name")
372     }
373     fn crate_hash(&self, cnum: CrateNum) -> Svh { bug!("crate_hash") }
374     fn crate_disambiguator(&self, cnum: CrateNum)
375                            -> Symbol { bug!("crate_disambiguator") }
376     fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
377         { bug!("plugin_registrar_fn") }
378     fn derive_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
379         { bug!("derive_registrar_fn") }
380     fn native_libraries(&self, cnum: CrateNum) -> Vec<NativeLibrary>
381         { bug!("native_libraries") }
382     fn exported_symbols(&self, cnum: CrateNum) -> Vec<DefId> { bug!("exported_symbols") }
383     fn is_no_builtins(&self, cnum: CrateNum) -> bool { bug!("is_no_builtins") }
384
385     // resolve
386     fn retrace_path(&self,
387                     cnum: CrateNum,
388                     path_data: &[DisambiguatedDefPathData])
389                     -> Option<DefId> {
390         None
391     }
392
393     fn def_key(&self, def: DefId) -> DefKey { bug!("def_key") }
394     fn def_path(&self, def: DefId) -> hir_map::DefPath {
395         bug!("relative_def_path")
396     }
397     fn def_path_hash(&self, def: DefId) -> u64 {
398         bug!("wa")
399     }
400     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name> { bug!("struct_field_names") }
401     fn item_children(&self, did: DefId) -> Vec<def::Export> { bug!("item_children") }
402     fn load_macro(&self, did: DefId, sess: &Session) -> LoadedMacro { bug!("load_macro") }
403
404     // misc. metadata
405     fn maybe_get_item_body<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, def: DefId)
406                                      -> Option<&'tcx hir::Body> {
407         bug!("maybe_get_item_body")
408     }
409     fn item_body_nested_bodies(&self, def: DefId) -> BTreeMap<hir::BodyId, hir::Body> {
410         bug!("item_body_nested_bodies")
411     }
412     fn const_is_rvalue_promotable_to_static(&self, def: DefId) -> bool {
413         bug!("const_is_rvalue_promotable_to_static")
414     }
415
416     fn is_item_mir_available(&self, def: DefId) -> bool {
417         bug!("is_item_mir_available")
418     }
419
420     // This is basically a 1-based range of ints, which is a little
421     // silly - I may fix that.
422     fn crates(&self) -> Vec<CrateNum> { vec![] }
423     fn used_libraries(&self) -> Vec<NativeLibrary> { vec![] }
424     fn used_link_args(&self) -> Vec<String> { vec![] }
425
426     // utility functions
427     fn metadata_filename(&self) -> &str { bug!("metadata_filename") }
428     fn metadata_section_name(&self, target: &Target) -> &str { bug!("metadata_section_name") }
429     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>
430         { vec![] }
431     fn used_crate_source(&self, cnum: CrateNum) -> CrateSource { bug!("used_crate_source") }
432     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum> { None }
433     fn encode_metadata<'a, 'tcx>(&self,
434                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
435                                  link_meta: &LinkMeta,
436                                  reachable: &NodeSet)
437                                  -> EncodedMetadata {
438         bug!("encode_metadata")
439     }
440     fn metadata_encoding_version(&self) -> &[u8] { bug!("metadata_encoding_version") }
441 }
442
443 pub trait CrateLoader {
444     fn process_item(&mut self, item: &ast::Item, defs: &Definitions);
445     fn postprocess(&mut self, krate: &ast::Crate);
446 }