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::edition::Edition;
38 use syntax::ext::base::SyntaxExtension;
39 use syntax::symbol::Symbol;
41 use rustc_target::spec::Target;
42 use rustc_data_structures::sync::{self, MetadataRef, Lrc};
44 pub use self::NativeLibraryKind::*;
46 // lonely orphan structs and enums looking for a better home
48 #[derive(Clone, Debug, Copy)]
53 /// Where a crate came from on the local filesystem. One of these three options
55 #[derive(PartialEq, Clone, Debug)]
56 pub struct CrateSource {
57 pub dylib: Option<(PathBuf, PathKind)>,
58 pub rlib: Option<(PathBuf, PathKind)>,
59 pub rmeta: Option<(PathBuf, PathKind)>,
62 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
64 /// A dependency that is only used for its macros, none of which are visible from other crates.
65 /// These are included in the metadata only as placeholders and are ignored when decoding.
67 /// A dependency that is only used for its macros.
69 /// A dependency that is always injected into the dependency list and so
70 /// doesn't need to be linked to an rlib, e.g. the injected allocator.
72 /// A dependency that is required by an rlib version of this crate.
73 /// Ordinary `extern crate`s result in `Explicit` dependencies.
78 pub fn macros_only(self) -> bool {
80 DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true,
81 DepKind::Implicit | DepKind::Explicit => false,
86 #[derive(PartialEq, Clone, Debug)]
94 pub fn is_some(&self) -> bool {
95 if let LibSource::Some(_) = *self {
102 pub fn option(&self) -> Option<PathBuf> {
104 LibSource::Some(ref p) => Some(p.clone()),
105 LibSource::MetadataOnly | LibSource::None => None,
110 #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
111 pub enum LinkagePreference {
116 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
117 pub enum NativeLibraryKind {
118 /// native static library (.a archive)
120 /// native static library, which doesn't get bundled into .rlibs
121 NativeStaticNobundle,
124 /// default way to specify a dynamic library
128 #[derive(Clone, RustcEncodable, RustcDecodable)]
129 pub struct NativeLibrary {
130 pub kind: NativeLibraryKind,
131 pub name: Option<Symbol>,
132 pub cfg: Option<ast::MetaItem>,
133 pub foreign_module: Option<DefId>,
134 pub wasm_import_module: Option<Symbol>,
137 #[derive(Clone, Hash, RustcEncodable, RustcDecodable)]
138 pub struct ForeignModule {
139 pub foreign_items: Vec<DefId>,
143 pub enum LoadedMacro {
145 ProcMacro(Lrc<SyntaxExtension>),
148 #[derive(Copy, Clone, Debug)]
149 pub struct ExternCrate {
150 pub src: ExternCrateSource,
152 /// span of the extern crate that caused this to be loaded
155 /// Number of links to reach the extern;
156 /// used to select the extern with the shortest path
159 /// If true, then this crate is the crate named by the extern
160 /// crate referenced above. If false, then this crate is a dep
165 #[derive(Copy, Clone, Debug)]
166 pub enum ExternCrateSource {
167 /// Crate is loaded by `extern crate`.
169 /// def_id of the item in the current crate that caused
170 /// this crate to be loaded; note that there could be multiple
174 // Crate is loaded by `use`.
176 /// Crate is implicitly loaded by an absolute or an `extern::` path.
180 pub struct EncodedMetadata {
181 pub raw_data: Vec<u8>
184 impl EncodedMetadata {
185 pub fn new() -> EncodedMetadata {
187 raw_data: Vec::new(),
192 /// The backend's way to give the crate store access to the metadata in a library.
193 /// Note that it returns the raw metadata bytes stored in the library file, whether
194 /// it is compressed, uncompressed, some weird mix, etc.
195 /// rmeta files are backend independent and not handled here.
197 /// At the time of this writing, there is only one backend and one way to store
198 /// metadata in library -- this trait just serves to decouple rustc_metadata from
199 /// the archive reader, which depends on LLVM.
200 pub trait MetadataLoader {
201 fn get_rlib_metadata(&self,
204 -> Result<MetadataRef, String>;
205 fn get_dylib_metadata(&self,
208 -> Result<MetadataRef, String>;
211 /// A store of Rust crates, through with their metadata
214 /// Note that this trait should probably not be expanding today. All new
215 /// functionality should be driven through queries instead!
217 /// If you find a method on this trait named `{name}_untracked` it signifies
218 /// that it's *not* tracked for dependency information throughout compilation
219 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
221 pub trait CrateStore {
222 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>;
224 // access to the metadata loader
225 fn metadata_loader(&self) -> &dyn MetadataLoader;
228 fn def_key(&self, def: DefId) -> DefKey;
229 fn def_path(&self, def: DefId) -> hir_map::DefPath;
230 fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash;
231 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable>;
233 // "queries" used in resolve that aren't tracked for incremental compilation
234 fn visibility_untracked(&self, def: DefId) -> ty::Visibility;
235 fn export_macros_untracked(&self, cnum: CrateNum);
236 fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind;
237 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol;
238 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator;
239 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh;
240 fn crate_edition_untracked(&self, cnum: CrateNum) -> Edition;
241 fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name>;
242 fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export>;
243 fn load_macro_untracked(&self, did: DefId, sess: &Session) -> LoadedMacro;
244 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
245 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics;
246 fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem;
247 fn postorder_cnums_untracked(&self) -> Vec<CrateNum>;
249 // This is basically a 1-based range of ints, which is a little
250 // silly - I may fix that.
251 fn crates_untracked(&self) -> Vec<CrateNum>;
254 fn encode_metadata<'a, 'tcx>(&self,
255 tcx: TyCtxt<'a, 'tcx, 'tcx>,
256 link_meta: &LinkMeta)
258 fn metadata_encoding_version(&self) -> &[u8];
261 pub type CrateStoreDyn = dyn CrateStore + sync::Sync;
263 // FIXME: find a better place for this?
264 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
265 let mut err_count = 0;
267 let mut say = |s: &str| {
269 (_, None) => bug!("{}", s),
270 (Some(sp), Some(sess)) => sess.span_err(sp, s),
271 (None, Some(sess)) => sess.err(s),
276 say("crate name must not be empty");
279 if c.is_alphanumeric() { continue }
280 if c == '_' { continue }
281 say(&format!("invalid character `{}` in crate name: `{}`", c, s));
286 sess.unwrap().abort_if_errors();
290 /// A dummy crate store that does not support any non-local crates,
291 /// for test purposes.
292 pub struct DummyCrateStore;
294 #[allow(unused_variables)]
295 impl CrateStore for DummyCrateStore {
296 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>
297 { bug!("crate_data_as_rc_any") }
299 fn visibility_untracked(&self, def: DefId) -> ty::Visibility { bug!("visibility") }
300 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics
301 { bug!("item_generics_cloned") }
303 // trait/impl-item info
304 fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem
305 { bug!("associated_item_cloned") }
308 fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind { bug!("is_explicitly_linked") }
309 fn export_macros_untracked(&self, cnum: CrateNum) { bug!("export_macros") }
310 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol { bug!("crate_name") }
311 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator {
312 bug!("crate_disambiguator")
314 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh { bug!("crate_hash") }
315 fn crate_edition_untracked(&self, cnum: CrateNum) -> Edition { bug!("crate_edition_untracked") }
318 fn def_key(&self, def: DefId) -> DefKey { bug!("def_key") }
319 fn def_path(&self, def: DefId) -> hir_map::DefPath {
320 bug!("relative_def_path")
322 fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash {
323 bug!("def_path_hash")
325 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
326 bug!("def_path_table")
328 fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
329 bug!("struct_field_names")
331 fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export> {
332 bug!("item_children")
334 fn load_macro_untracked(&self, did: DefId, sess: &Session) -> LoadedMacro { bug!("load_macro") }
336 fn crates_untracked(&self) -> Vec<CrateNum> { vec![] }
339 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum> { None }
340 fn encode_metadata<'a, 'tcx>(&self,
341 tcx: TyCtxt<'a, 'tcx, 'tcx>,
342 link_meta: &LinkMeta)
344 bug!("encode_metadata")
346 fn metadata_encoding_version(&self) -> &[u8] { bug!("metadata_encoding_version") }
347 fn postorder_cnums_untracked(&self) -> Vec<CrateNum> { bug!("postorder_cnums_untracked") }
349 // access to the metadata loader
350 fn metadata_loader(&self) -> &dyn MetadataLoader { bug!("metadata_loader") }
353 pub trait CrateLoader {
354 fn process_extern_crate(&mut self, item: &ast::Item, defs: &Definitions) -> CrateNum;
356 fn process_path_extern(
362 fn process_use_extern(
370 fn postprocess(&mut self, krate: &ast::Crate);
373 // This method is used when generating the command line to pass through to
374 // system linker. The linker expects undefined symbols on the left of the
375 // command line to be defined in libraries on the right, not the other way
376 // around. For more info, see some comments in the add_used_library function
379 // In order to get this left-to-right dependency ordering, we perform a
380 // topological sort of all crates putting the leaves at the right-most
382 pub fn used_crates(tcx: TyCtxt, prefer: LinkagePreference)
383 -> Vec<(CrateNum, LibSource)>
385 let mut libs = tcx.crates()
389 if tcx.dep_kind(cnum).macros_only() {
392 let source = tcx.used_crate_source(cnum);
393 let path = match prefer {
394 LinkagePreference::RequireDynamic => source.dylib.clone().map(|p| p.0),
395 LinkagePreference::RequireStatic => source.rlib.clone().map(|p| p.0),
397 let path = match path {
398 Some(p) => LibSource::Some(p),
400 if source.rmeta.is_some() {
401 LibSource::MetadataOnly
409 .collect::<Vec<_>>();
410 let mut ordering = tcx.postorder_cnums(LOCAL_CRATE);
411 Lrc::make_mut(&mut ordering).reverse();
412 libs.sort_by_cached_key(|&(a, _)| {
413 ordering.iter().position(|x| *x == a)