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