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