1 // Copyright 2012-2014 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 #![allow(non_camel_case_types)]
13 // The crate store - a central repo for information collected about external
14 // crates and libraries
16 pub use self::MetadataBlob::*;
17 pub use self::LinkagePreference::*;
18 pub use self::NativeLibraryKind::*;
21 use metadata::{creader, decoder, index, loader};
22 use session::search_paths::PathKind;
23 use util::nodemap::{FnvHashMap, NodeMap, NodeSet};
25 use std::cell::{RefCell, Ref, Cell};
27 use std::path::PathBuf;
32 use syntax::parse::token;
33 use syntax::parse::token::IdentInterner;
34 use syntax::util::small_vector::SmallVector;
35 use front::map as ast_map;
37 // A map from external crate numbers (as decoded from some crate file) to
38 // local crate numbers (as generated during this session). Each external
39 // crate may refer to types in other external crates, and each has their
41 pub type cnum_map = FnvHashMap<ast::CrateNum, ast::CrateNum>;
43 pub enum MetadataBlob {
45 MetadataArchive(loader::ArchiveMetadata),
48 /// Holds information about a codemap::FileMap imported from another crate.
49 /// See creader::import_codemap() for more information.
50 pub struct ImportedFileMap {
51 /// This FileMap's byte-offset within the codemap of its original crate
52 pub original_start_pos: codemap::BytePos,
53 /// The end of this FileMap within the codemap of its original crate
54 pub original_end_pos: codemap::BytePos,
55 /// The imported FileMap's representation within the local codemap
56 pub translated_filemap: Rc<codemap::FileMap>
59 pub struct crate_metadata {
61 pub local_path: RefCell<SmallVector<ast_map::PathElem>>,
62 pub data: MetadataBlob,
63 pub cnum_map: RefCell<cnum_map>,
64 pub cnum: ast::CrateNum,
65 pub codemap_import_info: RefCell<Vec<ImportedFileMap>>,
66 pub span: codemap::Span,
68 pub index: index::Index,
70 /// Flag if this crate is required by an rlib version of this crate, or in
71 /// other words whether it was explicitly linked to. An example of a crate
72 /// where this is false is when an allocator crate is injected into the
73 /// dependency list, and therefore isn't actually needed to link an rlib.
74 pub explicitly_linked: Cell<bool>,
77 #[derive(Copy, Debug, PartialEq, Clone)]
78 pub enum LinkagePreference {
84 #[derive(Copy, Clone, PartialEq)]
85 pub enum NativeLibraryKind {
86 NativeStatic, // native static library (.a archive)
87 NativeFramework, // OSX-specific
88 NativeUnknown, // default way to specify a dynamic library
92 // Where a crate came from on the local filesystem. One of these two options
94 #[derive(PartialEq, Clone)]
95 pub struct CrateSource {
96 pub dylib: Option<(PathBuf, PathKind)>,
97 pub rlib: Option<(PathBuf, PathKind)>,
98 pub cnum: ast::CrateNum,
102 metas: RefCell<FnvHashMap<ast::CrateNum, Rc<crate_metadata>>>,
103 /// Map from NodeId's of local extern crate statements to crate numbers
104 extern_mod_crate_map: RefCell<NodeMap<ast::CrateNum>>,
105 used_crate_sources: RefCell<Vec<CrateSource>>,
106 used_libraries: RefCell<Vec<(String, NativeLibraryKind)>>,
107 used_link_args: RefCell<Vec<String>>,
108 statically_included_foreign_items: RefCell<NodeSet>,
109 pub intr: Rc<IdentInterner>,
113 pub fn new(intr: Rc<IdentInterner>) -> CStore {
115 metas: RefCell::new(FnvHashMap()),
116 extern_mod_crate_map: RefCell::new(FnvHashMap()),
117 used_crate_sources: RefCell::new(Vec::new()),
118 used_libraries: RefCell::new(Vec::new()),
119 used_link_args: RefCell::new(Vec::new()),
121 statically_included_foreign_items: RefCell::new(NodeSet()),
125 pub fn next_crate_num(&self) -> ast::CrateNum {
126 self.metas.borrow().len() as ast::CrateNum + 1
129 pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> {
130 self.metas.borrow().get(&cnum).unwrap().clone()
133 pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh {
134 let cdata = self.get_crate_data(cnum);
135 decoder::get_crate_hash(cdata.data())
138 pub fn set_crate_data(&self, cnum: ast::CrateNum, data: Rc<crate_metadata>) {
139 self.metas.borrow_mut().insert(cnum, data);
142 pub fn iter_crate_data<I>(&self, mut i: I) where
143 I: FnMut(ast::CrateNum, &Rc<crate_metadata>),
145 for (&k, v) in self.metas.borrow().iter() {
150 /// Like `iter_crate_data`, but passes source paths (if available) as well.
151 pub fn iter_crate_data_origins<I>(&self, mut i: I) where
152 I: FnMut(ast::CrateNum, &crate_metadata, Option<CrateSource>),
154 for (&k, v) in self.metas.borrow().iter() {
155 let origin = self.get_used_crate_source(k);
156 origin.as_ref().map(|cs| { assert!(k == cs.cnum); });
161 pub fn add_used_crate_source(&self, src: CrateSource) {
162 let mut used_crate_sources = self.used_crate_sources.borrow_mut();
163 if !used_crate_sources.contains(&src) {
164 used_crate_sources.push(src);
168 pub fn get_used_crate_source(&self, cnum: ast::CrateNum)
169 -> Option<CrateSource> {
170 self.used_crate_sources.borrow_mut()
171 .iter().find(|source| source.cnum == cnum).cloned()
174 pub fn reset(&self) {
175 self.metas.borrow_mut().clear();
176 self.extern_mod_crate_map.borrow_mut().clear();
177 self.used_crate_sources.borrow_mut().clear();
178 self.used_libraries.borrow_mut().clear();
179 self.used_link_args.borrow_mut().clear();
180 self.statically_included_foreign_items.borrow_mut().clear();
183 // This method is used when generating the command line to pass through to
184 // system linker. The linker expects undefined symbols on the left of the
185 // command line to be defined in libraries on the right, not the other way
186 // around. For more info, see some comments in the add_used_library function
189 // In order to get this left-to-right dependency ordering, we perform a
190 // topological sort of all crates putting the leaves at the right-most
192 pub fn get_used_crates(&self, prefer: LinkagePreference)
193 -> Vec<(ast::CrateNum, Option<PathBuf>)> {
194 let mut ordering = Vec::new();
195 fn visit(cstore: &CStore, cnum: ast::CrateNum,
196 ordering: &mut Vec<ast::CrateNum>) {
197 if ordering.contains(&cnum) { return }
198 let meta = cstore.get_crate_data(cnum);
199 for (_, &dep) in meta.cnum_map.borrow().iter() {
200 visit(cstore, dep, ordering);
204 for (&num, _) in self.metas.borrow().iter() {
205 visit(self, num, &mut ordering);
207 info!("topological ordering: {:?}", ordering);
209 let mut libs = self.used_crate_sources.borrow()
211 .map(|src| (src.cnum, match prefer {
212 RequireDynamic => src.dylib.clone().map(|p| p.0),
213 RequireStatic => src.rlib.clone().map(|p| p.0),
215 .collect::<Vec<_>>();
216 libs.sort_by(|&(a, _), &(b, _)| {
217 let a = ordering.iter().position(|x| *x == a);
218 let b = ordering.iter().position(|x| *x == b);
224 pub fn add_used_library(&self, lib: String, kind: NativeLibraryKind) {
225 assert!(!lib.is_empty());
226 self.used_libraries.borrow_mut().push((lib, kind));
229 pub fn get_used_libraries<'a>(&'a self)
230 -> &'a RefCell<Vec<(String,
231 NativeLibraryKind)>> {
235 pub fn add_used_link_args(&self, args: &str) {
236 for s in args.split(' ').filter(|s| !s.is_empty()) {
237 self.used_link_args.borrow_mut().push(s.to_string());
241 pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<String> > {
245 pub fn add_extern_mod_stmt_cnum(&self,
246 emod_id: ast::NodeId,
247 cnum: ast::CrateNum) {
248 self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum);
251 pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId)
252 -> Option<ast::CrateNum> {
253 self.extern_mod_crate_map.borrow().get(&emod_id).cloned()
256 pub fn add_statically_included_foreign_item(&self, id: ast::NodeId) {
257 self.statically_included_foreign_items.borrow_mut().insert(id);
260 pub fn is_statically_included_foreign_item(&self, id: ast::NodeId) -> bool {
261 self.statically_included_foreign_items.borrow().contains(&id)
265 impl crate_metadata {
266 pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() }
267 pub fn name(&self) -> String { decoder::get_crate_name(self.data()) }
268 pub fn hash(&self) -> Svh { decoder::get_crate_hash(self.data()) }
269 pub fn imported_filemaps<'a>(&'a self, codemap: &codemap::CodeMap)
270 -> Ref<'a, Vec<ImportedFileMap>> {
271 let filemaps = self.codemap_import_info.borrow();
272 if filemaps.is_empty() {
274 let filemaps = creader::import_codemap(codemap, &self.data);
276 // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
277 *self.codemap_import_info.borrow_mut() = filemaps;
278 self.codemap_import_info.borrow()
284 pub fn with_local_path<T, F>(&self, f: F) -> T
285 where F: Fn(&[ast_map::PathElem]) -> T
287 let cpath = self.local_path.borrow();
288 if cpath.is_empty() {
289 let name = ast_map::PathMod(token::intern(&self.name));
296 pub fn update_local_path<'a, 'b>(&self, candidate: ast_map::PathElems<'a, 'b>) {
297 let mut cpath = self.local_path.borrow_mut();
298 let cap = cpath.len();
300 0 => *cpath = candidate.collect(),
303 let candidate: SmallVector<_> = candidate.collect();
304 if candidate.len() < cap {
311 pub fn is_allocator(&self) -> bool {
312 let attrs = decoder::get_crate_attributes(self.data());
313 attr::contains_name(&attrs, "allocator")
316 pub fn needs_allocator(&self) -> bool {
317 let attrs = decoder::get_crate_attributes(self.data());
318 attr::contains_name(&attrs, "needs_allocator")
323 pub fn as_slice<'a>(&'a self) -> &'a [u8] {
324 let slice = match *self {
325 MetadataVec(ref vec) => &vec[..],
326 MetadataArchive(ref ar) => ar.as_slice(),
329 &[] // corrupt metadata
331 let len = (((slice[0] as u32) << 24) |
332 ((slice[1] as u32) << 16) |
333 ((slice[2] as u32) << 8) |
334 ((slice[3] as u32) << 0)) as usize;
335 if len + 4 <= slice.len() {
338 &[] // corrupt or old metadata