]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/cstore.rs
Various minor/cosmetic improvements to code
[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_id::{CrateNum, DefId, LOCAL_CRATE};
26 use hir::map as hir_map;
27 use hir::map::definitions::{DefKey, DefPathTable};
28 use rustc_data_structures::svh::Svh;
29 use ty::{self, TyCtxt};
30 use session::{Session, CrateDisambiguator};
31 use session::search_paths::PathKind;
32
33 use std::any::Any;
34 use std::path::{Path, PathBuf};
35 use syntax::ast;
36 use syntax::symbol::Symbol;
37 use syntax_pos::Span;
38 use rustc_target::spec::Target;
39 use rustc_data_structures::sync::{self, MetadataRef, Lrc};
40
41 pub use self::NativeLibraryKind::*;
42
43 // lonely orphan structs and enums looking for a better home
44
45 /// Where a crate came from on the local filesystem. One of these three options
46 /// must be non-None.
47 #[derive(PartialEq, Clone, Debug)]
48 pub struct CrateSource {
49     pub dylib: Option<(PathBuf, PathKind)>,
50     pub rlib: Option<(PathBuf, PathKind)>,
51     pub rmeta: Option<(PathBuf, PathKind)>,
52 }
53
54 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
55 pub enum DepKind {
56     /// A dependency that is only used for its macros, none of which are visible from other crates.
57     /// These are included in the metadata only as placeholders and are ignored when decoding.
58     UnexportedMacrosOnly,
59     /// A dependency that is only used for its macros.
60     MacrosOnly,
61     /// A dependency that is always injected into the dependency list and so
62     /// doesn't need to be linked to an rlib, e.g., the injected allocator.
63     Implicit,
64     /// A dependency that is required by an rlib version of this crate.
65     /// Ordinary `extern crate`s result in `Explicit` dependencies.
66     Explicit,
67 }
68
69 impl DepKind {
70     pub fn macros_only(self) -> bool {
71         match self {
72             DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true,
73             DepKind::Implicit | DepKind::Explicit => false,
74         }
75     }
76 }
77
78 #[derive(PartialEq, Clone, Debug)]
79 pub enum LibSource {
80     Some(PathBuf),
81     MetadataOnly,
82     None,
83 }
84
85 impl LibSource {
86     pub fn is_some(&self) -> bool {
87         if let LibSource::Some(_) = *self {
88             true
89         } else {
90             false
91         }
92     }
93
94     pub fn option(&self) -> Option<PathBuf> {
95         match *self {
96             LibSource::Some(ref p) => Some(p.clone()),
97             LibSource::MetadataOnly | LibSource::None => None,
98         }
99     }
100 }
101
102 #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
103 pub enum LinkagePreference {
104     RequireDynamic,
105     RequireStatic,
106 }
107
108 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
109 pub enum NativeLibraryKind {
110     /// native static library (.a archive)
111     NativeStatic,
112     /// native static library, which doesn't get bundled into .rlibs
113     NativeStaticNobundle,
114     /// macOS-specific
115     NativeFramework,
116     /// default way to specify a dynamic library
117     NativeUnknown,
118 }
119
120 #[derive(Clone, RustcEncodable, RustcDecodable)]
121 pub struct NativeLibrary {
122     pub kind: NativeLibraryKind,
123     pub name: Option<Symbol>,
124     pub cfg: Option<ast::MetaItem>,
125     pub foreign_module: Option<DefId>,
126     pub wasm_import_module: Option<Symbol>,
127 }
128
129 #[derive(Clone, Hash, RustcEncodable, RustcDecodable)]
130 pub struct ForeignModule {
131     pub foreign_items: Vec<DefId>,
132     pub def_id: DefId,
133 }
134
135 #[derive(Copy, Clone, Debug)]
136 pub struct ExternCrate {
137     pub src: ExternCrateSource,
138
139     /// span of the extern crate that caused this to be loaded
140     pub span: Span,
141
142     /// Number of links to reach the extern;
143     /// used to select the extern with the shortest path
144     pub path_len: usize,
145
146     /// If true, then this crate is the crate named by the extern
147     /// crate referenced above. If false, then this crate is a dep
148     /// of the crate.
149     pub direct: bool,
150 }
151
152 #[derive(Copy, Clone, Debug)]
153 pub enum ExternCrateSource {
154     /// Crate is loaded by `extern crate`.
155     Extern(
156         /// def_id of the item in the current crate that caused
157         /// this crate to be loaded; note that there could be multiple
158         /// such ids
159         DefId,
160     ),
161     // Crate is loaded by `use`.
162     Use,
163     /// Crate is implicitly loaded by an absolute or an `extern::` path.
164     Path,
165 }
166
167 pub struct EncodedMetadata {
168     pub raw_data: Vec<u8>
169 }
170
171 impl EncodedMetadata {
172     pub fn new() -> EncodedMetadata {
173         EncodedMetadata {
174             raw_data: Vec::new(),
175         }
176     }
177 }
178
179 /// The backend's way to give the crate store access to the metadata in a library.
180 /// Note that it returns the raw metadata bytes stored in the library file, whether
181 /// it is compressed, uncompressed, some weird mix, etc.
182 /// rmeta files are backend independent and not handled here.
183 ///
184 /// At the time of this writing, there is only one backend and one way to store
185 /// metadata in library -- this trait just serves to decouple rustc_metadata from
186 /// the archive reader, which depends on LLVM.
187 pub trait MetadataLoader {
188     fn get_rlib_metadata(&self,
189                          target: &Target,
190                          filename: &Path)
191                          -> Result<MetadataRef, String>;
192     fn get_dylib_metadata(&self,
193                           target: &Target,
194                           filename: &Path)
195                           -> Result<MetadataRef, String>;
196 }
197
198 /// A store of Rust crates, through with their metadata
199 /// can be accessed.
200 ///
201 /// Note that this trait should probably not be expanding today. All new
202 /// functionality should be driven through queries instead!
203 ///
204 /// If you find a method on this trait named `{name}_untracked` it signifies
205 /// that it's *not* tracked for dependency information throughout compilation
206 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
207 /// during resolve)
208 pub trait CrateStore {
209     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>;
210
211     // resolve
212     fn def_key(&self, def: DefId) -> DefKey;
213     fn def_path(&self, def: DefId) -> hir_map::DefPath;
214     fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash;
215     fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable>;
216
217     // "queries" used in resolve that aren't tracked for incremental compilation
218     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol;
219     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator;
220     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh;
221     fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
222     fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics;
223     fn postorder_cnums_untracked(&self) -> Vec<CrateNum>;
224
225     // This is basically a 1-based range of ints, which is a little
226     // silly - I may fix that.
227     fn crates_untracked(&self) -> Vec<CrateNum>;
228
229     // utility functions
230     fn encode_metadata<'a, 'tcx>(&self,
231                                  tcx: TyCtxt<'a, 'tcx, 'tcx>)
232                                  -> EncodedMetadata;
233     fn metadata_encoding_version(&self) -> &[u8];
234 }
235
236 pub type CrateStoreDyn = dyn CrateStore + sync::Sync;
237
238 // This method is used when generating the command line to pass through to
239 // system linker. The linker expects undefined symbols on the left of the
240 // command line to be defined in libraries on the right, not the other way
241 // around. For more info, see some comments in the add_used_library function
242 // below.
243 //
244 // In order to get this left-to-right dependency ordering, we perform a
245 // topological sort of all crates putting the leaves at the right-most
246 // positions.
247 pub fn used_crates(tcx: TyCtxt<'_, '_, '_>, prefer: LinkagePreference)
248     -> Vec<(CrateNum, LibSource)>
249 {
250     let mut libs = tcx.crates()
251         .iter()
252         .cloned()
253         .filter_map(|cnum| {
254             if tcx.dep_kind(cnum).macros_only() {
255                 return None
256             }
257             let source = tcx.used_crate_source(cnum);
258             let path = match prefer {
259                 LinkagePreference::RequireDynamic => source.dylib.clone().map(|p| p.0),
260                 LinkagePreference::RequireStatic => source.rlib.clone().map(|p| p.0),
261             };
262             let path = match path {
263                 Some(p) => LibSource::Some(p),
264                 None => {
265                     if source.rmeta.is_some() {
266                         LibSource::MetadataOnly
267                     } else {
268                         LibSource::None
269                     }
270                 }
271             };
272             Some((cnum, path))
273         })
274         .collect::<Vec<_>>();
275     let mut ordering = tcx.postorder_cnums(LOCAL_CRATE);
276     Lrc::make_mut(&mut ordering).reverse();
277     libs.sort_by_cached_key(|&(a, _)| {
278         ordering.iter().position(|x| *x == a)
279     });
280     libs
281 }