]> git.lizzy.rs Git - rust.git/blob - src/librustc/metadata/cstore.rs
Use ast attributes every where (remove HIR attributes).
[rust.git] / src / librustc / metadata / cstore.rs
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.
4 //
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.
10
11 #![allow(non_camel_case_types)]
12
13 // The crate store - a central repo for information collected about external
14 // crates and libraries
15
16 pub use self::MetadataBlob::*;
17 pub use self::LinkagePreference::*;
18 pub use self::NativeLibraryKind::*;
19
20 use back::svh::Svh;
21 use metadata::{creader, decoder, index, loader};
22 use session::search_paths::PathKind;
23 use util::nodemap::{FnvHashMap, NodeMap, NodeSet};
24
25 use std::cell::{RefCell, Ref, Cell};
26 use std::rc::Rc;
27 use std::path::PathBuf;
28 use flate::Bytes;
29 use syntax::ast;
30 use syntax::attr;
31 use syntax::codemap;
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;
36
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
40 // own crate numbers.
41 pub type cnum_map = FnvHashMap<ast::CrateNum, ast::CrateNum>;
42
43 pub enum MetadataBlob {
44     MetadataVec(Bytes),
45     MetadataArchive(loader::ArchiveMetadata),
46 }
47
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>
57 }
58
59 pub struct crate_metadata {
60     pub name: String,
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,
67     pub staged_api: bool,
68     pub index: index::Index,
69
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>,
75 }
76
77 #[derive(Copy, Debug, PartialEq, Clone)]
78 pub enum LinkagePreference {
79     RequireDynamic,
80     RequireStatic,
81 }
82
83 enum_from_u32! {
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
89     }
90 }
91
92 // Where a crate came from on the local filesystem. One of these two options
93 // must be non-None.
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,
99 }
100
101 pub struct CStore {
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>,
110 }
111
112 impl CStore {
113     pub fn new(intr: Rc<IdentInterner>) -> CStore {
114         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()),
120             intr: intr,
121             statically_included_foreign_items: RefCell::new(NodeSet()),
122         }
123     }
124
125     pub fn next_crate_num(&self) -> ast::CrateNum {
126         self.metas.borrow().len() as ast::CrateNum + 1
127     }
128
129     pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> {
130         self.metas.borrow().get(&cnum).unwrap().clone()
131     }
132
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())
136     }
137
138     pub fn set_crate_data(&self, cnum: ast::CrateNum, data: Rc<crate_metadata>) {
139         self.metas.borrow_mut().insert(cnum, data);
140     }
141
142     pub fn iter_crate_data<I>(&self, mut i: I) where
143         I: FnMut(ast::CrateNum, &Rc<crate_metadata>),
144     {
145         for (&k, v) in self.metas.borrow().iter() {
146             i(k, v);
147         }
148     }
149
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>),
153     {
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); });
157             i(k, &**v, origin);
158         }
159     }
160
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);
165         }
166     }
167
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()
172     }
173
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();
181     }
182
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
187     // below.
188     //
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
191     // positions.
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);
201             }
202             ordering.push(cnum);
203         };
204         for (&num, _) in self.metas.borrow().iter() {
205             visit(self, num, &mut ordering);
206         }
207         info!("topological ordering: {:?}", ordering);
208         ordering.reverse();
209         let mut libs = self.used_crate_sources.borrow()
210             .iter()
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),
214             }))
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);
219             a.cmp(&b)
220         });
221         libs
222     }
223
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));
227     }
228
229     pub fn get_used_libraries<'a>(&'a self)
230                               -> &'a RefCell<Vec<(String,
231                                                   NativeLibraryKind)>> {
232         &self.used_libraries
233     }
234
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());
238         }
239     }
240
241     pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<String> > {
242         &self.used_link_args
243     }
244
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);
249     }
250
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()
254     }
255
256     pub fn add_statically_included_foreign_item(&self, id: ast::NodeId) {
257         self.statically_included_foreign_items.borrow_mut().insert(id);
258     }
259
260     pub fn is_statically_included_foreign_item(&self, id: ast::NodeId) -> bool {
261         self.statically_included_foreign_items.borrow().contains(&id)
262     }
263 }
264
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() {
273             drop(filemaps);
274             let filemaps = creader::import_codemap(codemap, &self.data);
275
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()
279         } else {
280             filemaps
281         }
282     }
283
284     pub fn with_local_path<T, F>(&self, f: F) -> T
285         where F: Fn(&[ast_map::PathElem]) -> T
286     {
287         let cpath = self.local_path.borrow();
288         if cpath.is_empty() {
289             let name = ast_map::PathMod(token::intern(&self.name));
290             f(&[name])
291         } else {
292             f(cpath.as_slice())
293         }
294     }
295
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();
299         match cap {
300             0 => *cpath = candidate.collect(),
301             1 => (),
302             _ => {
303                 let candidate: SmallVector<_> = candidate.collect();
304                 if candidate.len() < cap {
305                     *cpath = candidate;
306                 }
307             },
308         }
309     }
310
311     pub fn is_allocator(&self) -> bool {
312         let attrs = decoder::get_crate_attributes(self.data());
313         attr::contains_name(&attrs, "allocator")
314     }
315
316     pub fn needs_allocator(&self) -> bool {
317         let attrs = decoder::get_crate_attributes(self.data());
318         attr::contains_name(&attrs, "needs_allocator")
319     }
320 }
321
322 impl MetadataBlob {
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(),
327         };
328         if slice.len() < 4 {
329             &[] // corrupt metadata
330         } else {
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() {
336                 &slice[4.. len + 4]
337             } else {
338                 &[] // corrupt or old metadata
339             }
340         }
341     }
342 }