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.
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.
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.
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.
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.
26 use hir::def_id::{CrateNum, DefId, DefIndex};
27 use hir::map as hir_map;
28 use hir::map::definitions::{Definitions, DefKey, DefPathTable};
31 use ty::{self, TyCtxt};
33 use session::search_paths::PathKind;
34 use util::nodemap::{NodeSet, DefIdMap};
37 use std::path::{Path, PathBuf};
39 use owning_ref::ErasedBoxRef;
41 use syntax::ext::base::SyntaxExtension;
42 use syntax::symbol::Symbol;
44 use rustc_back::target::Target;
46 pub use self::NativeLibraryKind::*;
48 // lonely orphan structs and enums looking for a better home
50 #[derive(Clone, Debug, Copy)]
55 /// Where a crate came from on the local filesystem. One of these three options
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)>,
64 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
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.
69 /// A dependency that is only used for its macros.
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.
74 /// A dependency that is required by an rlib version of this crate.
75 /// Ordinary `extern crate`s result in `Explicit` dependencies.
80 pub fn macros_only(self) -> bool {
82 DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true,
83 DepKind::Implicit | DepKind::Explicit => false,
88 #[derive(PartialEq, Clone, Debug)]
96 pub fn is_some(&self) -> bool {
97 if let LibSource::Some(_) = *self {
104 pub fn option(&self) -> Option<PathBuf> {
106 LibSource::Some(ref p) => Some(p.clone()),
107 LibSource::MetadataOnly | LibSource::None => None,
112 #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
113 pub enum LinkagePreference {
118 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
119 pub enum NativeLibraryKind {
120 /// native static library (.a archive)
122 /// native static library, which doesn't get bundled into .rlibs
123 NativeStaticNobundle,
126 /// default way to specify a dynamic library
130 #[derive(Clone, Hash, RustcEncodable, RustcDecodable)]
131 pub struct NativeLibrary {
132 pub kind: NativeLibraryKind,
134 pub cfg: Option<ast::MetaItem>,
135 pub foreign_items: Vec<DefIndex>,
138 pub enum LoadedMacro {
140 ProcMacro(Rc<SyntaxExtension>),
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
150 /// span of the extern crate that caused this to be loaded
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
158 /// Number of links to reach the extern crate `def_id`
159 /// declaration; used to select the extern crate with the shortest
164 pub struct EncodedMetadata {
165 pub raw_data: Vec<u8>
168 impl EncodedMetadata {
169 pub fn new() -> EncodedMetadata {
171 raw_data: Vec::new(),
176 /// The hash for some metadata that (when saving) will be exported
177 /// from this crate, or which (when importing) was exported by an
179 #[derive(Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
180 pub struct EncodedMetadataHash {
181 pub def_index: DefIndex,
182 pub hash: ich::Fingerprint,
185 /// The hash for some metadata that (when saving) will be exported
186 /// from this crate, or which (when importing) was exported by an
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>,
194 impl EncodedMetadataHashes {
195 pub fn new() -> EncodedMetadataHashes {
196 EncodedMetadataHashes {
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.
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,
214 -> Result<ErasedBoxRef<[u8]>, String>;
215 fn get_dylib_metadata(&self,
218 -> Result<ErasedBoxRef<[u8]>, String>;
221 /// A store of Rust crates, through with their metadata
224 /// Note that this trait should probably not be expanding today. All new
225 /// functionality should be driven through queries instead!
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.
231 pub trait CrateStore {
232 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any>;
234 // access to the metadata loader
235 fn metadata_loader(&self) -> &MetadataLoader;
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;
241 // trait/impl-item info
242 fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem;
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>;
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>;
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>;
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,
271 -> (EncodedMetadata, EncodedMetadataHashes);
272 fn metadata_encoding_version(&self) -> &[u8];
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;
279 let mut say = |s: &str| {
281 (_, None) => bug!("{}", s),
282 (Some(sp), Some(sess)) => sess.span_err(sp, s),
283 (None, Some(sess)) => sess.err(s),
288 say("crate name must not be empty");
291 if c.is_alphanumeric() { continue }
292 if c == '_' { continue }
293 say(&format!("invalid character `{}` in crate name: `{}`", c, s));
298 sess.unwrap().abort_if_errors();
302 /// A dummy crate store that does not support any non-local crates,
303 /// for test purposes.
304 pub struct DummyCrateStore;
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") }
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>>
315 bug!("visible_parent_map")
317 fn item_generics_cloned(&self, def: DefId) -> ty::Generics
318 { bug!("item_generics_cloned") }
320 // trait/impl-item info
321 fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem
322 { bug!("associated_item_cloned") }
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") }
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")
334 fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash {
335 bug!("def_path_hash")
337 fn def_path_table(&self, cnum: CrateNum) -> Rc<DefPathTable> {
338 bug!("def_path_table")
340 fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
341 bug!("struct_field_names")
343 fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export> {
344 bug!("item_children")
346 fn load_macro_untracked(&self, did: DefId, sess: &Session) -> LoadedMacro { bug!("load_macro") }
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![] }
353 fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>
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,
361 -> (EncodedMetadata, EncodedMetadataHashes) {
362 bug!("encode_metadata")
364 fn metadata_encoding_version(&self) -> &[u8] { bug!("metadata_encoding_version") }
366 // access to the metadata loader
367 fn metadata_loader(&self) -> &MetadataLoader { bug!("metadata_loader") }
370 pub trait CrateLoader {
371 fn process_item(&mut self, item: &ast::Item, defs: &Definitions);
372 fn postprocess(&mut self, krate: &ast::Crate);