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