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