]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/cstore.rs
Rollup merge of #39604 - est31:i128_tests, r=alexcrichton
[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 // The crate store - a central repo for information collected about external
12 // crates and libraries
13
14 use locator;
15 use schema;
16
17 use rustc::dep_graph::DepGraph;
18 use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefIndex, DefId};
19 use rustc::hir::map::definitions::DefPathTable;
20 use rustc::hir::svh::Svh;
21 use rustc::middle::cstore::{DepKind, ExternCrate};
22 use rustc_back::PanicStrategy;
23 use rustc_data_structures::indexed_vec::IndexVec;
24 use rustc::util::nodemap::{FxHashMap, FxHashSet, NodeMap, DefIdMap};
25
26 use std::cell::{RefCell, Cell};
27 use std::rc::Rc;
28 use flate::Bytes;
29 use syntax::{ast, attr};
30 use syntax::ext::base::SyntaxExtension;
31 use syntax::symbol::Symbol;
32 use syntax_pos;
33
34 pub use rustc::middle::cstore::{NativeLibrary, NativeLibraryKind, LinkagePreference};
35 pub use rustc::middle::cstore::NativeLibraryKind::*;
36 pub use rustc::middle::cstore::{CrateSource, LinkMeta, LibSource};
37
38 // A map from external crate numbers (as decoded from some crate file) to
39 // local crate numbers (as generated during this session). Each external
40 // crate may refer to types in other external crates, and each has their
41 // own crate numbers.
42 pub type CrateNumMap = IndexVec<CrateNum, CrateNum>;
43
44 pub enum MetadataBlob {
45     Inflated(Bytes),
46     Archive(locator::ArchiveMetadata),
47     Raw(Vec<u8>),
48 }
49
50 /// Holds information about a syntax_pos::FileMap imported from another crate.
51 /// See `imported_filemaps()` for more information.
52 pub struct ImportedFileMap {
53     /// This FileMap's byte-offset within the codemap of its original crate
54     pub original_start_pos: syntax_pos::BytePos,
55     /// The end of this FileMap within the codemap of its original crate
56     pub original_end_pos: syntax_pos::BytePos,
57     /// The imported FileMap's representation within the local codemap
58     pub translated_filemap: Rc<syntax_pos::FileMap>,
59 }
60
61 pub struct CrateMetadata {
62     pub name: Symbol,
63
64     /// Information about the extern crate that caused this crate to
65     /// be loaded. If this is `None`, then the crate was injected
66     /// (e.g., by the allocator)
67     pub extern_crate: Cell<Option<ExternCrate>>,
68
69     pub blob: MetadataBlob,
70     pub cnum_map: RefCell<CrateNumMap>,
71     pub cnum: CrateNum,
72     pub codemap_import_info: RefCell<Vec<ImportedFileMap>>,
73
74     pub root: schema::CrateRoot,
75
76     /// For each public item in this crate, we encode a key.  When the
77     /// crate is loaded, we read all the keys and put them in this
78     /// hashmap, which gives the reverse mapping.  This allows us to
79     /// quickly retrace a `DefPath`, which is needed for incremental
80     /// compilation support.
81     pub def_path_table: DefPathTable,
82
83     pub exported_symbols: FxHashSet<DefIndex>,
84
85     pub dep_kind: Cell<DepKind>,
86     pub source: CrateSource,
87
88     pub proc_macros: Option<Vec<(ast::Name, Rc<SyntaxExtension>)>>,
89     // Foreign items imported from a dylib (Windows only)
90     pub dllimport_foreign_items: FxHashSet<DefIndex>,
91 }
92
93 pub struct CStore {
94     pub dep_graph: DepGraph,
95     metas: RefCell<FxHashMap<CrateNum, Rc<CrateMetadata>>>,
96     /// Map from NodeId's of local extern crate statements to crate numbers
97     extern_mod_crate_map: RefCell<NodeMap<CrateNum>>,
98     used_libraries: RefCell<Vec<NativeLibrary>>,
99     used_link_args: RefCell<Vec<String>>,
100     statically_included_foreign_items: RefCell<FxHashSet<DefIndex>>,
101     pub dllimport_foreign_items: RefCell<FxHashSet<DefIndex>>,
102     pub visible_parent_map: RefCell<DefIdMap<DefId>>,
103 }
104
105 impl CStore {
106     pub fn new(dep_graph: &DepGraph) -> CStore {
107         CStore {
108             dep_graph: dep_graph.clone(),
109             metas: RefCell::new(FxHashMap()),
110             extern_mod_crate_map: RefCell::new(FxHashMap()),
111             used_libraries: RefCell::new(Vec::new()),
112             used_link_args: RefCell::new(Vec::new()),
113             statically_included_foreign_items: RefCell::new(FxHashSet()),
114             dllimport_foreign_items: RefCell::new(FxHashSet()),
115             visible_parent_map: RefCell::new(FxHashMap()),
116         }
117     }
118
119     pub fn next_crate_num(&self) -> CrateNum {
120         CrateNum::new(self.metas.borrow().len() + 1)
121     }
122
123     pub fn get_crate_data(&self, cnum: CrateNum) -> Rc<CrateMetadata> {
124         self.metas.borrow().get(&cnum).unwrap().clone()
125     }
126
127     pub fn get_crate_hash(&self, cnum: CrateNum) -> Svh {
128         self.get_crate_data(cnum).hash()
129     }
130
131     pub fn set_crate_data(&self, cnum: CrateNum, data: Rc<CrateMetadata>) {
132         self.metas.borrow_mut().insert(cnum, data);
133     }
134
135     pub fn iter_crate_data<I>(&self, mut i: I)
136         where I: FnMut(CrateNum, &Rc<CrateMetadata>)
137     {
138         for (&k, v) in self.metas.borrow().iter() {
139             i(k, v);
140         }
141     }
142
143     pub fn reset(&self) {
144         self.metas.borrow_mut().clear();
145         self.extern_mod_crate_map.borrow_mut().clear();
146         self.used_libraries.borrow_mut().clear();
147         self.used_link_args.borrow_mut().clear();
148         self.statically_included_foreign_items.borrow_mut().clear();
149     }
150
151     pub fn crate_dependencies_in_rpo(&self, krate: CrateNum) -> Vec<CrateNum> {
152         let mut ordering = Vec::new();
153         self.push_dependencies_in_postorder(&mut ordering, krate);
154         ordering.reverse();
155         ordering
156     }
157
158     pub fn push_dependencies_in_postorder(&self, ordering: &mut Vec<CrateNum>, krate: CrateNum) {
159         if ordering.contains(&krate) {
160             return;
161         }
162
163         let data = self.get_crate_data(krate);
164         for &dep in data.cnum_map.borrow().iter() {
165             if dep != krate {
166                 self.push_dependencies_in_postorder(ordering, dep);
167             }
168         }
169
170         ordering.push(krate);
171     }
172
173     // This method is used when generating the command line to pass through to
174     // system linker. The linker expects undefined symbols on the left of the
175     // command line to be defined in libraries on the right, not the other way
176     // around. For more info, see some comments in the add_used_library function
177     // below.
178     //
179     // In order to get this left-to-right dependency ordering, we perform a
180     // topological sort of all crates putting the leaves at the right-most
181     // positions.
182     pub fn do_get_used_crates(&self,
183                               prefer: LinkagePreference)
184                               -> Vec<(CrateNum, LibSource)> {
185         let mut ordering = Vec::new();
186         for (&num, _) in self.metas.borrow().iter() {
187             self.push_dependencies_in_postorder(&mut ordering, num);
188         }
189         info!("topological ordering: {:?}", ordering);
190         ordering.reverse();
191         let mut libs = self.metas
192             .borrow()
193             .iter()
194             .filter_map(|(&cnum, data)| {
195                 if data.dep_kind.get().macros_only() { return None; }
196                 let path = match prefer {
197                     LinkagePreference::RequireDynamic => data.source.dylib.clone().map(|p| p.0),
198                     LinkagePreference::RequireStatic => data.source.rlib.clone().map(|p| p.0),
199                 };
200                 let path = match path {
201                     Some(p) => LibSource::Some(p),
202                     None => {
203                         if data.source.rmeta.is_some() {
204                             LibSource::MetadataOnly
205                         } else {
206                             LibSource::None
207                         }
208                     }
209                 };
210                 Some((cnum, path))
211             })
212             .collect::<Vec<_>>();
213         libs.sort_by(|&(a, _), &(b, _)| {
214             let a = ordering.iter().position(|x| *x == a);
215             let b = ordering.iter().position(|x| *x == b);
216             a.cmp(&b)
217         });
218         libs
219     }
220
221     pub fn add_used_library(&self, lib: NativeLibrary) {
222         assert!(!lib.name.as_str().is_empty());
223         self.used_libraries.borrow_mut().push(lib);
224     }
225
226     pub fn get_used_libraries(&self) -> &RefCell<Vec<NativeLibrary>> {
227         &self.used_libraries
228     }
229
230     pub fn add_used_link_args(&self, args: &str) {
231         for s in args.split(' ').filter(|s| !s.is_empty()) {
232             self.used_link_args.borrow_mut().push(s.to_string());
233         }
234     }
235
236     pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<String>> {
237         &self.used_link_args
238     }
239
240     pub fn add_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId, cnum: CrateNum) {
241         self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum);
242     }
243
244     pub fn add_statically_included_foreign_item(&self, id: DefIndex) {
245         self.statically_included_foreign_items.borrow_mut().insert(id);
246     }
247
248     pub fn do_is_statically_included_foreign_item(&self, def_id: DefId) -> bool {
249         assert!(def_id.krate == LOCAL_CRATE);
250         self.statically_included_foreign_items.borrow().contains(&def_id.index)
251     }
252
253     pub fn do_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum> {
254         self.extern_mod_crate_map.borrow().get(&emod_id).cloned()
255     }
256 }
257
258 impl CrateMetadata {
259     pub fn name(&self) -> Symbol {
260         self.root.name
261     }
262     pub fn hash(&self) -> Svh {
263         self.root.hash
264     }
265     pub fn disambiguator(&self) -> Symbol {
266         self.root.disambiguator
267     }
268
269     pub fn is_staged_api(&self) -> bool {
270         self.get_item_attrs(CRATE_DEF_INDEX)
271             .iter()
272             .any(|attr| attr.name() == "stable" || attr.name() == "unstable")
273     }
274
275     pub fn is_allocator(&self) -> bool {
276         let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
277         attr::contains_name(&attrs, "allocator")
278     }
279
280     pub fn needs_allocator(&self) -> bool {
281         let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
282         attr::contains_name(&attrs, "needs_allocator")
283     }
284
285     pub fn is_panic_runtime(&self) -> bool {
286         let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
287         attr::contains_name(&attrs, "panic_runtime")
288     }
289
290     pub fn needs_panic_runtime(&self) -> bool {
291         let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
292         attr::contains_name(&attrs, "needs_panic_runtime")
293     }
294
295     pub fn is_compiler_builtins(&self) -> bool {
296         let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
297         attr::contains_name(&attrs, "compiler_builtins")
298     }
299
300     pub fn is_sanitizer_runtime(&self) -> bool {
301         let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
302         attr::contains_name(&attrs, "sanitizer_runtime")
303     }
304
305     pub fn is_no_builtins(&self) -> bool {
306         let attrs = self.get_item_attrs(CRATE_DEF_INDEX);
307         attr::contains_name(&attrs, "no_builtins")
308     }
309
310     pub fn panic_strategy(&self) -> PanicStrategy {
311         self.root.panic_strategy.clone()
312     }
313 }