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