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;
35 use util::nodemap::NodeSet;
38 use std::collections::BTreeMap;
39 use std::path::{Path, PathBuf};
40 use rustc_data_structures::owning_ref::ErasedBoxRef;
42 use syntax::ext::base::SyntaxExtension;
43 use syntax::symbol::Symbol;
45 use rustc_back::target::Target;
46 use rustc_data_structures::sync::Lrc;
48 pub use self::NativeLibraryKind::*;
50 // lonely orphan structs and enums looking for a better home
52 #[derive(Clone, Debug, Copy)]
57 /// Where a crate came from on the local filesystem. One of these three options
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)>,
66 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
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.
71 /// A dependency that is only used for its macros.
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.
76 /// A dependency that is required by an rlib version of this crate.
77 /// Ordinary `extern crate`s result in `Explicit` dependencies.
82 pub fn macros_only(self) -> bool {
84 DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true,
85 DepKind::Implicit | DepKind::Explicit => false,
90 #[derive(PartialEq, Clone, Debug)]
98 pub fn is_some(&self) -> bool {
99 if let LibSource::Some(_) = *self {
106 pub fn option(&self) -> Option<PathBuf> {
108 LibSource::Some(ref p) => Some(p.clone()),
109 LibSource::MetadataOnly | LibSource::None => None,
114 #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
115 pub enum LinkagePreference {
120 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
121 pub enum NativeLibraryKind {
122 /// native static library (.a archive)
124 /// native static library, which doesn't get bundled into .rlibs
125 NativeStaticNobundle,
128 /// default way to specify a dynamic library
132 #[derive(Clone, Hash, RustcEncodable, RustcDecodable)]
133 pub struct NativeLibrary {
134 pub kind: NativeLibraryKind,
136 pub cfg: Option<ast::MetaItem>,
137 pub foreign_items: Vec<DefId>,
140 pub enum LoadedMacro {
142 ProcMacro(Lrc<SyntaxExtension>),
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
152 /// span of the extern crate that caused this to be loaded
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
160 /// Number of links to reach the extern crate `def_id`
161 /// declaration; used to select the extern crate with the shortest
166 pub struct EncodedMetadata {
167 pub raw_data: Vec<u8>
170 impl EncodedMetadata {
171 pub fn new() -> EncodedMetadata {
173 raw_data: Vec::new(),
178 /// The backend's way to give the crate store access to the metadata in a library.
179 /// Note that it returns the raw metadata bytes stored in the library file, whether
180 /// it is compressed, uncompressed, some weird mix, etc.
181 /// rmeta files are backend independent and not handled here.
183 /// At the time of this writing, there is only one backend and one way to store
184 /// metadata in library -- this trait just serves to decouple rustc_metadata from
185 /// the archive reader, which depends on LLVM.
186 pub trait MetadataLoader {
187 fn get_rlib_metadata(&self,
190 -> Result<ErasedBoxRef<[u8]>, String>;
191 fn get_dylib_metadata(&self,
194 -> Result<ErasedBoxRef<[u8]>, String>;
198 pub struct ExternConstBody<'tcx> {
199 pub body: &'tcx hir::Body,
201 // It would require a lot of infrastructure to enable stable-hashing Bodies
202 // from other crates, so we hash on export and just store the fingerprint
204 pub fingerprint: ich::Fingerprint,
208 pub struct ExternBodyNestedBodies {
209 pub nested_bodies: Lrc<BTreeMap<hir::BodyId, hir::Body>>,
211 // It would require a lot of infrastructure to enable stable-hashing Bodies
212 // from other crates, so we hash on export and just store the fingerprint
214 pub fingerprint: ich::Fingerprint,
217 /// A store of Rust crates, through with their metadata
220 /// Note that this trait should probably not be expanding today. All new
221 /// functionality should be driven through queries instead!
223 /// If you find a method on this trait named `{name}_untracked` it signifies
224 /// that it's *not* tracked for dependency information throughout compilation
225 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
227 pub trait CrateStore {
228 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>;
230 // access to the metadata loader
231 fn metadata_loader(&self) -> &dyn MetadataLoader;
234 fn def_key(&self, def: DefId) -> DefKey;
235 fn def_path(&self, def: DefId) -> hir_map::DefPath;
236 fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash;
237 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable>;
239 // "queries" used in resolve that aren't tracked for incremental compilation
240 fn visibility_untracked(&self, def: DefId) -> ty::Visibility;
241 fn export_macros_untracked(&self, cnum: CrateNum);
242 fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind;
243 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol;
244 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator;
245 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh;
246 fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name>;
247 fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export>;
248 fn load_macro_untracked(&self, did: DefId, sess: &Session) -> LoadedMacro;
249 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
250 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics;
251 fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem;
252 fn postorder_cnums_untracked(&self) -> Vec<CrateNum>;
254 // This is basically a 1-based range of ints, which is a little
255 // silly - I may fix that.
256 fn crates_untracked(&self) -> Vec<CrateNum>;
259 fn encode_metadata<'a, 'tcx>(&self,
260 tcx: TyCtxt<'a, 'tcx, 'tcx>,
261 link_meta: &LinkMeta,
264 fn metadata_encoding_version(&self) -> &[u8];
267 // FIXME: find a better place for this?
268 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
269 let mut err_count = 0;
271 let mut say = |s: &str| {
273 (_, None) => bug!("{}", s),
274 (Some(sp), Some(sess)) => sess.span_err(sp, s),
275 (None, Some(sess)) => sess.err(s),
280 say("crate name must not be empty");
283 if c.is_alphanumeric() { continue }
284 if c == '_' { continue }
285 say(&format!("invalid character `{}` in crate name: `{}`", c, s));
290 sess.unwrap().abort_if_errors();
294 /// A dummy crate store that does not support any non-local crates,
295 /// for test purposes.
296 pub struct DummyCrateStore;
298 #[allow(unused_variables)]
299 impl CrateStore for DummyCrateStore {
300 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>
301 { bug!("crate_data_as_rc_any") }
303 fn visibility_untracked(&self, def: DefId) -> ty::Visibility { bug!("visibility") }
304 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics
305 { bug!("item_generics_cloned") }
307 // trait/impl-item info
308 fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem
309 { bug!("associated_item_cloned") }
312 fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind { bug!("is_explicitly_linked") }
313 fn export_macros_untracked(&self, cnum: CrateNum) { bug!("export_macros") }
314 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol { bug!("crate_name") }
315 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator {
316 bug!("crate_disambiguator")
318 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh { bug!("crate_hash") }
321 fn def_key(&self, def: DefId) -> DefKey { bug!("def_key") }
322 fn def_path(&self, def: DefId) -> hir_map::DefPath {
323 bug!("relative_def_path")
325 fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash {
326 bug!("def_path_hash")
328 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
329 bug!("def_path_table")
331 fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
332 bug!("struct_field_names")
334 fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export> {
335 bug!("item_children")
337 fn load_macro_untracked(&self, did: DefId, sess: &Session) -> LoadedMacro { bug!("load_macro") }
339 fn crates_untracked(&self) -> Vec<CrateNum> { vec![] }
342 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum> { None }
343 fn encode_metadata<'a, 'tcx>(&self,
344 tcx: TyCtxt<'a, 'tcx, 'tcx>,
345 link_meta: &LinkMeta,
348 bug!("encode_metadata")
350 fn metadata_encoding_version(&self) -> &[u8] { bug!("metadata_encoding_version") }
351 fn postorder_cnums_untracked(&self) -> Vec<CrateNum> { bug!("postorder_cnums_untracked") }
353 // access to the metadata loader
354 fn metadata_loader(&self) -> &dyn MetadataLoader { bug!("metadata_loader") }
357 pub trait CrateLoader {
358 fn process_item(&mut self, item: &ast::Item, defs: &Definitions);
359 fn postprocess(&mut self, krate: &ast::Crate);
360 fn resolve_crate_from_path(&mut self, name: Symbol, span: Span) -> CrateNum;
363 // This method is used when generating the command line to pass through to
364 // system linker. The linker expects undefined symbols on the left of the
365 // command line to be defined in libraries on the right, not the other way
366 // around. For more info, see some comments in the add_used_library function
369 // In order to get this left-to-right dependency ordering, we perform a
370 // topological sort of all crates putting the leaves at the right-most
372 pub fn used_crates(tcx: TyCtxt, prefer: LinkagePreference)
373 -> Vec<(CrateNum, LibSource)>
375 let mut libs = tcx.crates()
379 if tcx.dep_kind(cnum).macros_only() {
382 let source = tcx.used_crate_source(cnum);
383 let path = match prefer {
384 LinkagePreference::RequireDynamic => source.dylib.clone().map(|p| p.0),
385 LinkagePreference::RequireStatic => source.rlib.clone().map(|p| p.0),
387 let path = match path {
388 Some(p) => LibSource::Some(p),
390 if source.rmeta.is_some() {
391 LibSource::MetadataOnly
399 .collect::<Vec<_>>();
400 let mut ordering = tcx.postorder_cnums(LOCAL_CRATE);
401 Lrc::make_mut(&mut ordering).reverse();
402 libs.sort_by_key(|&(a, _)| {
403 ordering.iter().position(|x| *x == a)