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