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, LOCAL_CRATE};
27 use hir::map as hir_map;
28 use hir::map::definitions::{Definitions, DefKey, DefPathTable};
30 use ty::{self, TyCtxt};
31 use session::{Session, CrateDisambiguator};
32 use session::search_paths::PathKind;
35 use std::path::{Path, PathBuf};
37 use syntax::ext::base::SyntaxExtension;
38 use syntax::symbol::Symbol;
40 use rustc_target::spec::Target;
41 use rustc_data_structures::sync::{MetadataRef, Lrc};
43 pub use self::NativeLibraryKind::*;
45 // lonely orphan structs and enums looking for a better home
47 #[derive(Clone, Debug, Copy)]
52 /// Where a crate came from on the local filesystem. One of these three options
54 #[derive(PartialEq, Clone, Debug)]
55 pub struct CrateSource {
56 pub dylib: Option<(PathBuf, PathKind)>,
57 pub rlib: Option<(PathBuf, PathKind)>,
58 pub rmeta: Option<(PathBuf, PathKind)>,
61 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
63 /// A dependency that is only used for its macros, none of which are visible from other crates.
64 /// These are included in the metadata only as placeholders and are ignored when decoding.
66 /// A dependency that is only used for its macros.
68 /// A dependency that is always injected into the dependency list and so
69 /// doesn't need to be linked to an rlib, e.g. the injected allocator.
71 /// A dependency that is required by an rlib version of this crate.
72 /// Ordinary `extern crate`s result in `Explicit` dependencies.
77 pub fn macros_only(self) -> bool {
79 DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true,
80 DepKind::Implicit | DepKind::Explicit => false,
85 #[derive(PartialEq, Clone, Debug)]
93 pub fn is_some(&self) -> bool {
94 if let LibSource::Some(_) = *self {
101 pub fn option(&self) -> Option<PathBuf> {
103 LibSource::Some(ref p) => Some(p.clone()),
104 LibSource::MetadataOnly | LibSource::None => None,
109 #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
110 pub enum LinkagePreference {
115 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
116 pub enum NativeLibraryKind {
117 /// native static library (.a archive)
119 /// native static library, which doesn't get bundled into .rlibs
120 NativeStaticNobundle,
123 /// default way to specify a dynamic library
127 #[derive(Clone, Hash, RustcEncodable, RustcDecodable)]
128 pub struct NativeLibrary {
129 pub kind: NativeLibraryKind,
131 pub cfg: Option<ast::MetaItem>,
132 pub foreign_module: Option<DefId>,
135 #[derive(Clone, Hash, RustcEncodable, RustcDecodable)]
136 pub struct ForeignModule {
137 pub foreign_items: Vec<DefId>,
141 pub enum LoadedMacro {
143 ProcMacro(Lrc<SyntaxExtension>),
146 #[derive(Copy, Clone, Debug)]
147 pub struct ExternCrate {
148 pub src: ExternCrateSource,
150 /// span of the extern crate that caused this to be loaded
153 /// Number of links to reach the extern;
154 /// used to select the extern with the shortest path
157 /// If true, then this crate is the crate named by the extern
158 /// crate referenced above. If false, then this crate is a dep
163 #[derive(Copy, Clone, Debug)]
164 pub enum ExternCrateSource {
165 /// Crate is loaded by `extern crate`.
167 /// def_id of the item in the current crate that caused
168 /// this crate to be loaded; note that there could be multiple
172 // Crate is loaded by `use`.
174 /// Crate is implicitly loaded by an absolute or an `extern::` path.
178 pub struct EncodedMetadata {
179 pub raw_data: Vec<u8>
182 impl EncodedMetadata {
183 pub fn new() -> EncodedMetadata {
185 raw_data: Vec::new(),
190 /// The backend's way to give the crate store access to the metadata in a library.
191 /// Note that it returns the raw metadata bytes stored in the library file, whether
192 /// it is compressed, uncompressed, some weird mix, etc.
193 /// rmeta files are backend independent and not handled here.
195 /// At the time of this writing, there is only one backend and one way to store
196 /// metadata in library -- this trait just serves to decouple rustc_metadata from
197 /// the archive reader, which depends on LLVM.
198 pub trait MetadataLoader {
199 fn get_rlib_metadata(&self,
202 -> Result<MetadataRef, String>;
203 fn get_dylib_metadata(&self,
206 -> Result<MetadataRef, String>;
209 /// A store of Rust crates, through with their metadata
212 /// Note that this trait should probably not be expanding today. All new
213 /// functionality should be driven through queries instead!
215 /// If you find a method on this trait named `{name}_untracked` it signifies
216 /// that it's *not* tracked for dependency information throughout compilation
217 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
219 pub trait CrateStore {
220 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>;
222 // access to the metadata loader
223 fn metadata_loader(&self) -> &dyn MetadataLoader;
226 fn def_key(&self, def: DefId) -> DefKey;
227 fn def_path(&self, def: DefId) -> hir_map::DefPath;
228 fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash;
229 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable>;
231 // "queries" used in resolve that aren't tracked for incremental compilation
232 fn visibility_untracked(&self, def: DefId) -> ty::Visibility;
233 fn export_macros_untracked(&self, cnum: CrateNum);
234 fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind;
235 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol;
236 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator;
237 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh;
238 fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name>;
239 fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export>;
240 fn load_macro_untracked(&self, did: DefId, sess: &Session) -> LoadedMacro;
241 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
242 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics;
243 fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem;
244 fn postorder_cnums_untracked(&self) -> Vec<CrateNum>;
246 // This is basically a 1-based range of ints, which is a little
247 // silly - I may fix that.
248 fn crates_untracked(&self) -> Vec<CrateNum>;
251 fn encode_metadata<'a, 'tcx>(&self,
252 tcx: TyCtxt<'a, 'tcx, 'tcx>,
253 link_meta: &LinkMeta)
255 fn metadata_encoding_version(&self) -> &[u8];
258 // FIXME: find a better place for this?
259 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
260 let mut err_count = 0;
262 let mut say = |s: &str| {
264 (_, None) => bug!("{}", s),
265 (Some(sp), Some(sess)) => sess.span_err(sp, s),
266 (None, Some(sess)) => sess.err(s),
271 say("crate name must not be empty");
274 if c.is_alphanumeric() { continue }
275 if c == '_' { continue }
276 say(&format!("invalid character `{}` in crate name: `{}`", c, s));
281 sess.unwrap().abort_if_errors();
285 /// A dummy crate store that does not support any non-local crates,
286 /// for test purposes.
287 pub struct DummyCrateStore;
289 #[allow(unused_variables)]
290 impl CrateStore for DummyCrateStore {
291 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>
292 { bug!("crate_data_as_rc_any") }
294 fn visibility_untracked(&self, def: DefId) -> ty::Visibility { bug!("visibility") }
295 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics
296 { bug!("item_generics_cloned") }
298 // trait/impl-item info
299 fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem
300 { bug!("associated_item_cloned") }
303 fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind { bug!("is_explicitly_linked") }
304 fn export_macros_untracked(&self, cnum: CrateNum) { bug!("export_macros") }
305 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol { bug!("crate_name") }
306 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator {
307 bug!("crate_disambiguator")
309 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh { bug!("crate_hash") }
312 fn def_key(&self, def: DefId) -> DefKey { bug!("def_key") }
313 fn def_path(&self, def: DefId) -> hir_map::DefPath {
314 bug!("relative_def_path")
316 fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash {
317 bug!("def_path_hash")
319 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
320 bug!("def_path_table")
322 fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
323 bug!("struct_field_names")
325 fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export> {
326 bug!("item_children")
328 fn load_macro_untracked(&self, did: DefId, sess: &Session) -> LoadedMacro { bug!("load_macro") }
330 fn crates_untracked(&self) -> Vec<CrateNum> { vec![] }
333 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum> { None }
334 fn encode_metadata<'a, 'tcx>(&self,
335 tcx: TyCtxt<'a, 'tcx, 'tcx>,
336 link_meta: &LinkMeta)
338 bug!("encode_metadata")
340 fn metadata_encoding_version(&self) -> &[u8] { bug!("metadata_encoding_version") }
341 fn postorder_cnums_untracked(&self) -> Vec<CrateNum> { bug!("postorder_cnums_untracked") }
343 // access to the metadata loader
344 fn metadata_loader(&self) -> &dyn MetadataLoader { bug!("metadata_loader") }
347 pub trait CrateLoader {
348 fn process_extern_crate(&mut self, item: &ast::Item, defs: &Definitions) -> CrateNum;
350 fn process_path_extern(
356 fn process_use_extern(
364 fn postprocess(&mut self, krate: &ast::Crate);
367 // This method is used when generating the command line to pass through to
368 // system linker. The linker expects undefined symbols on the left of the
369 // command line to be defined in libraries on the right, not the other way
370 // around. For more info, see some comments in the add_used_library function
373 // In order to get this left-to-right dependency ordering, we perform a
374 // topological sort of all crates putting the leaves at the right-most
376 pub fn used_crates(tcx: TyCtxt, prefer: LinkagePreference)
377 -> Vec<(CrateNum, LibSource)>
379 let mut libs = tcx.crates()
383 if tcx.dep_kind(cnum).macros_only() {
386 let source = tcx.used_crate_source(cnum);
387 let path = match prefer {
388 LinkagePreference::RequireDynamic => source.dylib.clone().map(|p| p.0),
389 LinkagePreference::RequireStatic => source.rlib.clone().map(|p| p.0),
391 let path = match path {
392 Some(p) => LibSource::Some(p),
394 if source.rmeta.is_some() {
395 LibSource::MetadataOnly
403 .collect::<Vec<_>>();
404 let mut ordering = tcx.postorder_cnums(LOCAL_CRATE);
405 Lrc::make_mut(&mut ordering).reverse();
406 libs.sort_by_cached_key(|&(a, _)| {
407 ordering.iter().position(|x| *x == a)