1 //! the rustc crate store interface. This also includes types that
2 //! are *mostly* used as a part of that interface, but these should
3 //! probably get a better home if someone can find one.
5 use crate::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
6 use crate::hir::map as hir_map;
7 use crate::hir::map::definitions::{DefKey, DefPathTable};
8 use rustc_data_structures::svh::Svh;
9 use crate::ty::{self, TyCtxt};
10 use crate::session::{Session, CrateDisambiguator};
11 use crate::session::search_paths::PathKind;
14 use std::path::{Path, PathBuf};
16 use syntax::symbol::Symbol;
18 use rustc_target::spec::Target;
19 use rustc_data_structures::sync::{self, MetadataRef, Lrc};
21 pub use self::NativeLibraryKind::*;
23 // lonely orphan structs and enums looking for a better home
25 /// Where a crate came from on the local filesystem. One of these three options
27 #[derive(PartialEq, Clone, Debug)]
28 pub struct CrateSource {
29 pub dylib: Option<(PathBuf, PathKind)>,
30 pub rlib: Option<(PathBuf, PathKind)>,
31 pub rmeta: Option<(PathBuf, PathKind)>,
34 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
36 /// A dependency that is only used for its macros, none of which are visible from other crates.
37 /// These are included in the metadata only as placeholders and are ignored when decoding.
39 /// A dependency that is only used for its macros.
41 /// A dependency that is always injected into the dependency list and so
42 /// doesn't need to be linked to an rlib, e.g., the injected allocator.
44 /// A dependency that is required by an rlib version of this crate.
45 /// Ordinary `extern crate`s result in `Explicit` dependencies.
50 pub fn macros_only(self) -> bool {
52 DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true,
53 DepKind::Implicit | DepKind::Explicit => false,
58 #[derive(PartialEq, Clone, Debug)]
66 pub fn is_some(&self) -> bool {
67 if let LibSource::Some(_) = *self {
74 pub fn option(&self) -> Option<PathBuf> {
76 LibSource::Some(ref p) => Some(p.clone()),
77 LibSource::MetadataOnly | LibSource::None => None,
82 #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
83 pub enum LinkagePreference {
88 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
89 pub enum NativeLibraryKind {
90 /// native static library (.a archive)
92 /// native static library, which doesn't get bundled into .rlibs
96 /// default way to specify a dynamic library
100 #[derive(Clone, RustcEncodable, RustcDecodable)]
101 pub struct NativeLibrary {
102 pub kind: NativeLibraryKind,
103 pub name: Option<Symbol>,
104 pub cfg: Option<ast::MetaItem>,
105 pub foreign_module: Option<DefId>,
106 pub wasm_import_module: Option<Symbol>,
109 #[derive(Clone, Hash, RustcEncodable, RustcDecodable)]
110 pub struct ForeignModule {
111 pub foreign_items: Vec<DefId>,
115 #[derive(Copy, Clone, Debug)]
116 pub struct ExternCrate {
117 pub src: ExternCrateSource,
119 /// span of the extern crate that caused this to be loaded
122 /// Number of links to reach the extern;
123 /// used to select the extern with the shortest path
126 /// If true, then this crate is the crate named by the extern
127 /// crate referenced above. If false, then this crate is a dep
132 #[derive(Copy, Clone, Debug)]
133 pub enum ExternCrateSource {
134 /// Crate is loaded by `extern crate`.
136 /// def_id of the item in the current crate that caused
137 /// this crate to be loaded; note that there could be multiple
141 // Crate is loaded by `use`.
143 /// Crate is implicitly loaded by an absolute path.
147 pub struct EncodedMetadata {
148 pub raw_data: Vec<u8>
151 impl EncodedMetadata {
152 pub fn new() -> EncodedMetadata {
154 raw_data: Vec::new(),
159 /// The backend's way to give the crate store access to the metadata in a library.
160 /// Note that it returns the raw metadata bytes stored in the library file, whether
161 /// it is compressed, uncompressed, some weird mix, etc.
162 /// rmeta files are backend independent and not handled here.
164 /// At the time of this writing, there is only one backend and one way to store
165 /// metadata in library -- this trait just serves to decouple rustc_metadata from
166 /// the archive reader, which depends on LLVM.
167 pub trait MetadataLoader {
168 fn get_rlib_metadata(&self,
171 -> Result<MetadataRef, String>;
172 fn get_dylib_metadata(&self,
175 -> Result<MetadataRef, String>;
178 /// A store of Rust crates, through with their metadata
181 /// Note that this trait should probably not be expanding today. All new
182 /// functionality should be driven through queries instead!
184 /// If you find a method on this trait named `{name}_untracked` it signifies
185 /// that it's *not* tracked for dependency information throughout compilation
186 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
188 pub trait CrateStore {
189 fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>;
192 fn def_key(&self, def: DefId) -> DefKey;
193 fn def_path(&self, def: DefId) -> hir_map::DefPath;
194 fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash;
195 fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable>;
197 // "queries" used in resolve that aren't tracked for incremental compilation
198 fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol;
199 fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator;
200 fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh;
201 fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
202 fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics;
203 fn postorder_cnums_untracked(&self) -> Vec<CrateNum>;
205 // This is basically a 1-based range of ints, which is a little
206 // silly - I may fix that.
207 fn crates_untracked(&self) -> Vec<CrateNum>;
210 fn encode_metadata<'a, 'tcx>(&self,
211 tcx: TyCtxt<'a, 'tcx, 'tcx>)
213 fn metadata_encoding_version(&self) -> &[u8];
216 pub type CrateStoreDyn = dyn CrateStore + sync::Sync;
218 // This method is used when generating the command line to pass through to
219 // system linker. The linker expects undefined symbols on the left of the
220 // command line to be defined in libraries on the right, not the other way
221 // around. For more info, see some comments in the add_used_library function
224 // In order to get this left-to-right dependency ordering, we perform a
225 // topological sort of all crates putting the leaves at the right-most
227 pub fn used_crates(tcx: TyCtxt<'_, '_, '_>, prefer: LinkagePreference)
228 -> Vec<(CrateNum, LibSource)>
230 let mut libs = tcx.crates()
234 if tcx.dep_kind(cnum).macros_only() {
237 let source = tcx.used_crate_source(cnum);
238 let path = match prefer {
239 LinkagePreference::RequireDynamic => source.dylib.clone().map(|p| p.0),
240 LinkagePreference::RequireStatic => source.rlib.clone().map(|p| p.0),
242 let path = match path {
243 Some(p) => LibSource::Some(p),
245 if source.rmeta.is_some() {
246 LibSource::MetadataOnly
254 .collect::<Vec<_>>();
255 let mut ordering = tcx.postorder_cnums(LOCAL_CRATE);
256 Lrc::make_mut(&mut ordering).reverse();
257 libs.sort_by_cached_key(|&(a, _)| {
258 ordering.iter().position(|x| *x == a)