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