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