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