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