]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/cstore.rs
Merge branch 'refactor-select' of https://github.com/aravind-pg/rust into update...
[rust.git] / src / librustc / middle / cstore.rs
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.
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 // 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.
14 //
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.
20
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.
24
25 use hir;
26 use hir::def;
27 use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
28 use hir::map as hir_map;
29 use hir::map::definitions::{Definitions, DefKey, DefPathTable};
30 use hir::svh::Svh;
31 use ich;
32 use ty::{self, TyCtxt};
33 use session::{Session, CrateDisambiguator};
34 use session::search_paths::PathKind;
35
36 use std::any::Any;
37 use std::collections::BTreeMap;
38 use std::path::{Path, PathBuf};
39 use rustc_data_structures::owning_ref::ErasedBoxRef;
40 use syntax::ast;
41 use syntax::ext::base::SyntaxExtension;
42 use syntax::symbol::Symbol;
43 use syntax_pos::Span;
44 use rustc_back::target::Target;
45 use rustc_data_structures::sync::Lrc;
46
47 pub use self::NativeLibraryKind::*;
48
49 // lonely orphan structs and enums looking for a better home
50
51 #[derive(Clone, Debug, Copy)]
52 pub struct LinkMeta {
53     pub crate_hash: Svh,
54 }
55
56 /// Where a crate came from on the local filesystem. One of these three options
57 /// must be non-None.
58 #[derive(PartialEq, Clone, Debug)]
59 pub struct CrateSource {
60     pub dylib: Option<(PathBuf, PathKind)>,
61     pub rlib: Option<(PathBuf, PathKind)>,
62     pub rmeta: Option<(PathBuf, PathKind)>,
63 }
64
65 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
66 pub enum DepKind {
67     /// A dependency that is only used for its macros, none of which are visible from other crates.
68     /// These are included in the metadata only as placeholders and are ignored when decoding.
69     UnexportedMacrosOnly,
70     /// A dependency that is only used for its macros.
71     MacrosOnly,
72     /// A dependency that is always injected into the dependency list and so
73     /// doesn't need to be linked to an rlib, e.g. the injected allocator.
74     Implicit,
75     /// A dependency that is required by an rlib version of this crate.
76     /// Ordinary `extern crate`s result in `Explicit` dependencies.
77     Explicit,
78 }
79
80 impl DepKind {
81     pub fn macros_only(self) -> bool {
82         match self {
83             DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true,
84             DepKind::Implicit | DepKind::Explicit => false,
85         }
86     }
87 }
88
89 #[derive(PartialEq, Clone, Debug)]
90 pub enum LibSource {
91     Some(PathBuf),
92     MetadataOnly,
93     None,
94 }
95
96 impl LibSource {
97     pub fn is_some(&self) -> bool {
98         if let LibSource::Some(_) = *self {
99             true
100         } else {
101             false
102         }
103     }
104
105     pub fn option(&self) -> Option<PathBuf> {
106         match *self {
107             LibSource::Some(ref p) => Some(p.clone()),
108             LibSource::MetadataOnly | LibSource::None => None,
109         }
110     }
111 }
112
113 #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
114 pub enum LinkagePreference {
115     RequireDynamic,
116     RequireStatic,
117 }
118
119 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
120 pub enum NativeLibraryKind {
121     /// native static library (.a archive)
122     NativeStatic,
123     /// native static library, which doesn't get bundled into .rlibs
124     NativeStaticNobundle,
125     /// macOS-specific
126     NativeFramework,
127     /// default way to specify a dynamic library
128     NativeUnknown,
129 }
130
131 #[derive(Clone, Hash, RustcEncodable, RustcDecodable)]
132 pub struct NativeLibrary {
133     pub kind: NativeLibraryKind,
134     pub name: Symbol,
135     pub cfg: Option<ast::MetaItem>,
136     pub foreign_items: Vec<DefId>,
137 }
138
139 pub enum LoadedMacro {
140     MacroDef(ast::Item),
141     ProcMacro(Lrc<SyntaxExtension>),
142 }
143
144 #[derive(Copy, Clone, Debug)]
145 pub struct ExternCrate {
146     /// def_id of an `extern crate` in the current crate that caused
147     /// this crate to be loaded; note that there could be multiple
148     /// such ids
149     pub def_id: DefId,
150
151     /// span of the extern crate that caused this to be loaded
152     pub span: Span,
153
154     /// If true, then this crate is the crate named by the extern
155     /// crate referenced above. If false, then this crate is a dep
156     /// of the crate.
157     pub direct: bool,
158
159     /// Number of links to reach the extern crate `def_id`
160     /// declaration; used to select the extern crate with the shortest
161     /// path
162     pub path_len: usize,
163 }
164
165 pub struct EncodedMetadata {
166     pub raw_data: Vec<u8>
167 }
168
169 impl EncodedMetadata {
170     pub fn new() -> EncodedMetadata {
171         EncodedMetadata {
172             raw_data: Vec::new(),
173         }
174     }
175 }
176
177 /// The backend's way to give the crate store access to the metadata in a library.
178 /// Note that it returns the raw metadata bytes stored in the library file, whether
179 /// it is compressed, uncompressed, some weird mix, etc.
180 /// rmeta files are backend independent and not handled here.
181 ///
182 /// At the time of this writing, there is only one backend and one way to store
183 /// metadata in library -- this trait just serves to decouple rustc_metadata from
184 /// the archive reader, which depends on LLVM.
185 pub trait MetadataLoader {
186     fn get_rlib_metadata(&self,
187                          target: &Target,
188                          filename: &Path)
189                          -> Result<ErasedBoxRef<[u8]>, String>;
190     fn get_dylib_metadata(&self,
191                           target: &Target,
192                           filename: &Path)
193                           -> Result<ErasedBoxRef<[u8]>, String>;
194 }
195
196 #[derive(Clone)]
197 pub struct ExternConstBody<'tcx> {
198     pub body: &'tcx hir::Body,
199
200     // It would require a lot of infrastructure to enable stable-hashing Bodies
201     // from other crates, so we hash on export and just store the fingerprint
202     // with them.
203     pub fingerprint: ich::Fingerprint,
204 }
205
206 #[derive(Clone)]
207 pub struct ExternBodyNestedBodies {
208     pub nested_bodies: Lrc<BTreeMap<hir::BodyId, hir::Body>>,
209
210     // It would require a lot of infrastructure to enable stable-hashing Bodies
211     // from other crates, so we hash on export and just store the fingerprint
212     // with them.
213     pub fingerprint: ich::Fingerprint,
214 }
215
216 /// A store of Rust crates, through with their metadata
217 /// can be accessed.
218 ///
219 /// Note that this trait should probably not be expanding today. All new
220 /// functionality should be driven through queries instead!
221 ///
222 /// If you find a method on this trait named `{name}_untracked` it signifies
223 /// that it's *not* tracked for dependency information throughout compilation
224 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
225 /// during resolve)
226 pub trait CrateStore {
227     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>;
228
229     // access to the metadata loader
230     fn metadata_loader(&self) -> &dyn MetadataLoader;
231
232     // resolve
233     fn def_key(&self, def: DefId) -> DefKey;
234     fn def_path(&self, def: DefId) -> hir_map::DefPath;
235     fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash;
236     fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable>;
237
238     // "queries" used in resolve that aren't tracked for incremental compilation
239     fn visibility_untracked(&self, def: DefId) -> ty::Visibility;
240     fn export_macros_untracked(&self, cnum: CrateNum);
241     fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind;
242     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol;
243     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator;
244     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh;
245     fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name>;
246     fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export>;
247     fn load_macro_untracked(&self, did: DefId, sess: &Session) -> LoadedMacro;
248     fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
249     fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics;
250     fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem;
251     fn postorder_cnums_untracked(&self) -> Vec<CrateNum>;
252
253     // This is basically a 1-based range of ints, which is a little
254     // silly - I may fix that.
255     fn crates_untracked(&self) -> Vec<CrateNum>;
256
257     // utility functions
258     fn encode_metadata<'a, 'tcx>(&self,
259                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
260                                  link_meta: &LinkMeta)
261                                  -> EncodedMetadata;
262     fn metadata_encoding_version(&self) -> &[u8];
263 }
264
265 // FIXME: find a better place for this?
266 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
267     let mut err_count = 0;
268     {
269         let mut say = |s: &str| {
270             match (sp, sess) {
271                 (_, None) => bug!("{}", s),
272                 (Some(sp), Some(sess)) => sess.span_err(sp, s),
273                 (None, Some(sess)) => sess.err(s),
274             }
275             err_count += 1;
276         };
277         if s.is_empty() {
278             say("crate name must not be empty");
279         }
280         for c in s.chars() {
281             if c.is_alphanumeric() { continue }
282             if c == '_'  { continue }
283             say(&format!("invalid character `{}` in crate name: `{}`", c, s));
284         }
285     }
286
287     if err_count > 0 {
288         sess.unwrap().abort_if_errors();
289     }
290 }
291
292 /// A dummy crate store that does not support any non-local crates,
293 /// for test purposes.
294 pub struct DummyCrateStore;
295
296 #[allow(unused_variables)]
297 impl CrateStore for DummyCrateStore {
298     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>
299         { bug!("crate_data_as_rc_any") }
300     // item info
301     fn visibility_untracked(&self, def: DefId) -> ty::Visibility { bug!("visibility") }
302     fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics
303         { bug!("item_generics_cloned") }
304
305     // trait/impl-item info
306     fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem
307         { bug!("associated_item_cloned") }
308
309     // crate metadata
310     fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind { bug!("is_explicitly_linked") }
311     fn export_macros_untracked(&self, cnum: CrateNum) { bug!("export_macros") }
312     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol { bug!("crate_name") }
313     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator {
314         bug!("crate_disambiguator")
315     }
316     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh { bug!("crate_hash") }
317
318     // resolve
319     fn def_key(&self, def: DefId) -> DefKey { bug!("def_key") }
320     fn def_path(&self, def: DefId) -> hir_map::DefPath {
321         bug!("relative_def_path")
322     }
323     fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash {
324         bug!("def_path_hash")
325     }
326     fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
327         bug!("def_path_table")
328     }
329     fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
330         bug!("struct_field_names")
331     }
332     fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export> {
333         bug!("item_children")
334     }
335     fn load_macro_untracked(&self, did: DefId, sess: &Session) -> LoadedMacro { bug!("load_macro") }
336
337     fn crates_untracked(&self) -> Vec<CrateNum> { vec![] }
338
339     // utility functions
340     fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum> { None }
341     fn encode_metadata<'a, 'tcx>(&self,
342                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
343                                  link_meta: &LinkMeta)
344                                  -> EncodedMetadata {
345         bug!("encode_metadata")
346     }
347     fn metadata_encoding_version(&self) -> &[u8] { bug!("metadata_encoding_version") }
348     fn postorder_cnums_untracked(&self) -> Vec<CrateNum> { bug!("postorder_cnums_untracked") }
349
350     // access to the metadata loader
351     fn metadata_loader(&self) -> &dyn MetadataLoader { bug!("metadata_loader") }
352 }
353
354 pub trait CrateLoader {
355     fn process_item(&mut self, item: &ast::Item, defs: &Definitions);
356     fn postprocess(&mut self, krate: &ast::Crate);
357     fn resolve_crate_from_path(&mut self, name: Symbol, span: Span) -> CrateNum;
358 }
359
360 // This method is used when generating the command line to pass through to
361 // system linker. The linker expects undefined symbols on the left of the
362 // command line to be defined in libraries on the right, not the other way
363 // around. For more info, see some comments in the add_used_library function
364 // below.
365 //
366 // In order to get this left-to-right dependency ordering, we perform a
367 // topological sort of all crates putting the leaves at the right-most
368 // positions.
369 pub fn used_crates(tcx: TyCtxt, prefer: LinkagePreference)
370     -> Vec<(CrateNum, LibSource)>
371 {
372     let mut libs = tcx.crates()
373         .iter()
374         .cloned()
375         .filter_map(|cnum| {
376             if tcx.dep_kind(cnum).macros_only() {
377                 return None
378             }
379             let source = tcx.used_crate_source(cnum);
380             let path = match prefer {
381                 LinkagePreference::RequireDynamic => source.dylib.clone().map(|p| p.0),
382                 LinkagePreference::RequireStatic => source.rlib.clone().map(|p| p.0),
383             };
384             let path = match path {
385                 Some(p) => LibSource::Some(p),
386                 None => {
387                     if source.rmeta.is_some() {
388                         LibSource::MetadataOnly
389                     } else {
390                         LibSource::None
391                     }
392                 }
393             };
394             Some((cnum, path))
395         })
396         .collect::<Vec<_>>();
397     let mut ordering = tcx.postorder_cnums(LOCAL_CRATE);
398     Lrc::make_mut(&mut ordering).reverse();
399     libs.sort_by_key(|&(a, _)| {
400         ordering.iter().position(|x| *x == a)
401     });
402     libs
403 }