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.
27 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
28 use hir::map as hir_map;
29 use hir::map::definitions::{Definitions, DefKey, DefPathTable};
32 use ty::{self, TyCtxt};
33 use session::{Session, CrateDisambiguator};
34 use session::search_paths::PathKind;
37 use std::collections::BTreeMap;
38 use std::path::{Path, PathBuf};
39 use rustc_data_structures::owning_ref::ErasedBoxRef;
41 use syntax::ext::base::SyntaxExtension;
42 use syntax::symbol::Symbol;
44 use rustc_back::target::Target;
45 use rustc_data_structures::sync::Lrc;
47 pub use self::NativeLibraryKind::*;
49 // lonely orphan structs and enums looking for a better home
51 #[derive(Clone, Debug, Copy)]
56 /// Where a crate came from on the local filesystem. One of these three options
58 #[derive(PartialEq, Clone, Debug)]
59 pub struct CrateSource {
60 pub dylib: Option<(PathBuf, PathKind)>,
61 pub rlib: Option<(PathBuf, PathKind)>,
62 pub rmeta: Option<(PathBuf, PathKind)>,
65 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
67 /// A dependency that is only used for its macros, none of which are visible from other crates.
68 /// These are included in the metadata only as placeholders and are ignored when decoding.
70 /// A dependency that is only used for its macros.
72 /// A dependency that is always injected into the dependency list and so
73 /// doesn't need to be linked to an rlib, e.g. the injected allocator.
75 /// A dependency that is required by an rlib version of this crate.
76 /// Ordinary `extern crate`s result in `Explicit` dependencies.
81 pub fn macros_only(self) -> bool {
83 DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true,
84 DepKind::Implicit | DepKind::Explicit => false,
89 #[derive(PartialEq, Clone, Debug)]
97 pub fn is_some(&self) -> bool {
98 if let LibSource::Some(_) = *self {
105 pub fn option(&self) -> Option<PathBuf> {
107 LibSource::Some(ref p) => Some(p.clone()),
108 LibSource::MetadataOnly | LibSource::None => None,
113 #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
114 pub enum LinkagePreference {
119 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
120 pub enum NativeLibraryKind {
121 /// native static library (.a archive)
123 /// native static library, which doesn't get bundled into .rlibs
124 NativeStaticNobundle,
127 /// default way to specify a dynamic library
131 #[derive(Clone, Hash, RustcEncodable, RustcDecodable)]
132 pub struct NativeLibrary {
133 pub kind: NativeLibraryKind,
135 pub cfg: Option<ast::MetaItem>,
136 pub foreign_items: Vec<DefId>,
139 pub enum LoadedMacro {
141 ProcMacro(Lrc<SyntaxExtension>),
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
151 /// span of the extern crate that caused this to be loaded
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
159 /// Number of links to reach the extern crate `def_id`
160 /// declaration; used to select the extern crate with the shortest
165 pub struct EncodedMetadata {
166 pub raw_data: Vec<u8>
169 impl EncodedMetadata {
170 pub fn new() -> EncodedMetadata {
172 raw_data: Vec::new(),
177 /// The backend's way to give the crate store access to the metadata in a library.
178 /// Note that it returns the raw metadata bytes stored in the library file, whether
179 /// it is compressed, uncompressed, some weird mix, etc.
180 /// rmeta files are backend independent and not handled here.
182 /// At the time of this writing, there is only one backend and one way to store
183 /// metadata in library -- this trait just serves to decouple rustc_metadata from
184 /// the archive reader, which depends on LLVM.
185 pub trait MetadataLoader {
186 fn get_rlib_metadata(&self,
189 -> Result<ErasedBoxRef<[u8]>, String>;
190 fn get_dylib_metadata(&self,
193 -> Result<ErasedBoxRef<[u8]>, String>;
197 pub struct ExternConstBody<'tcx> {
198 pub body: &'tcx hir::Body,
200 // It would require a lot of infrastructure to enable stable-hashing Bodies
201 // from other crates, so we hash on export and just store the fingerprint
203 pub fingerprint: ich::Fingerprint,
207 pub struct ExternBodyNestedBodies {
208 pub nested_bodies: Lrc<BTreeMap<hir::BodyId, hir::Body>>,
210 // It would require a lot of infrastructure to enable stable-hashing Bodies
211 // from other crates, so we hash on export and just store the fingerprint
213 pub fingerprint: ich::Fingerprint,
216 /// A store of Rust crates, through with their metadata
219 /// Note that this trait should probably not be expanding today. All new
220 /// functionality should be driven through queries instead!
222 /// If you find a method on this trait named `{name}_untracked` it signifies
223 /// that it's *not* tracked for dependency information throughout compilation
224 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
226 pub trait CrateStore {
227 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>;
229 // access to the metadata loader
230 fn metadata_loader(&self) -> &dyn MetadataLoader;
233 fn def_key(&self, def: DefId) -> DefKey;
234 fn def_path(&self, def: DefId) -> hir_map::DefPath;
235 fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash;
236 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable>;
238 // "queries" used in resolve that aren't tracked for incremental compilation
239 fn visibility_untracked(&self, def: DefId) -> ty::Visibility;
240 fn export_macros_untracked(&self, cnum: CrateNum);
241 fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind;
242 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol;
243 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator;
244 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh;
245 fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name>;
246 fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export>;
247 fn load_macro_untracked(&self, did: DefId, sess: &Session) -> LoadedMacro;
248 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
249 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics;
250 fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem;
251 fn postorder_cnums_untracked(&self) -> Vec<CrateNum>;
253 // This is basically a 1-based range of ints, which is a little
254 // silly - I may fix that.
255 fn crates_untracked(&self) -> Vec<CrateNum>;
258 fn encode_metadata<'a, 'tcx>(&self,
259 tcx: TyCtxt<'a, 'tcx, 'tcx>,
260 link_meta: &LinkMeta)
262 fn metadata_encoding_version(&self) -> &[u8];
265 // FIXME: find a better place for this?
266 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
267 let mut err_count = 0;
269 let mut say = |s: &str| {
271 (_, None) => bug!("{}", s),
272 (Some(sp), Some(sess)) => sess.span_err(sp, s),
273 (None, Some(sess)) => sess.err(s),
278 say("crate name must not be empty");
281 if c.is_alphanumeric() { continue }
282 if c == '_' { continue }
283 say(&format!("invalid character `{}` in crate name: `{}`", c, s));
288 sess.unwrap().abort_if_errors();
292 /// A dummy crate store that does not support any non-local crates,
293 /// for test purposes.
294 pub struct DummyCrateStore;
296 #[allow(unused_variables)]
297 impl CrateStore for DummyCrateStore {
298 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>
299 { bug!("crate_data_as_rc_any") }
301 fn visibility_untracked(&self, def: DefId) -> ty::Visibility { bug!("visibility") }
302 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics
303 { bug!("item_generics_cloned") }
305 // trait/impl-item info
306 fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem
307 { bug!("associated_item_cloned") }
310 fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind { bug!("is_explicitly_linked") }
311 fn export_macros_untracked(&self, cnum: CrateNum) { bug!("export_macros") }
312 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol { bug!("crate_name") }
313 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator {
314 bug!("crate_disambiguator")
316 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh { bug!("crate_hash") }
319 fn def_key(&self, def: DefId) -> DefKey { bug!("def_key") }
320 fn def_path(&self, def: DefId) -> hir_map::DefPath {
321 bug!("relative_def_path")
323 fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash {
324 bug!("def_path_hash")
326 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
327 bug!("def_path_table")
329 fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
330 bug!("struct_field_names")
332 fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export> {
333 bug!("item_children")
335 fn load_macro_untracked(&self, did: DefId, sess: &Session) -> LoadedMacro { bug!("load_macro") }
337 fn crates_untracked(&self) -> Vec<CrateNum> { vec![] }
340 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum> { None }
341 fn encode_metadata<'a, 'tcx>(&self,
342 tcx: TyCtxt<'a, 'tcx, 'tcx>,
343 link_meta: &LinkMeta)
345 bug!("encode_metadata")
347 fn metadata_encoding_version(&self) -> &[u8] { bug!("metadata_encoding_version") }
348 fn postorder_cnums_untracked(&self) -> Vec<CrateNum> { bug!("postorder_cnums_untracked") }
350 // access to the metadata loader
351 fn metadata_loader(&self) -> &dyn MetadataLoader { bug!("metadata_loader") }
354 pub trait CrateLoader {
355 fn process_item(&mut self, item: &ast::Item, defs: &Definitions);
356 fn postprocess(&mut self, krate: &ast::Crate);
357 fn resolve_crate_from_path(&mut self, name: Symbol, span: Span) -> CrateNum;
360 // This method is used when generating the command line to pass through to
361 // system linker. The linker expects undefined symbols on the left of the
362 // command line to be defined in libraries on the right, not the other way
363 // around. For more info, see some comments in the add_used_library function
366 // In order to get this left-to-right dependency ordering, we perform a
367 // topological sort of all crates putting the leaves at the right-most
369 pub fn used_crates(tcx: TyCtxt, prefer: LinkagePreference)
370 -> Vec<(CrateNum, LibSource)>
372 let mut libs = tcx.crates()
376 if tcx.dep_kind(cnum).macros_only() {
379 let source = tcx.used_crate_source(cnum);
380 let path = match prefer {
381 LinkagePreference::RequireDynamic => source.dylib.clone().map(|p| p.0),
382 LinkagePreference::RequireStatic => source.rlib.clone().map(|p| p.0),
384 let path = match path {
385 Some(p) => LibSource::Some(p),
387 if source.rmeta.is_some() {
388 LibSource::MetadataOnly
396 .collect::<Vec<_>>();
397 let mut ordering = tcx.postorder_cnums(LOCAL_CRATE);
398 Lrc::make_mut(&mut ordering).reverse();
399 libs.sort_by_key(|&(a, _)| {
400 ordering.iter().position(|x| *x == a)