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