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