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