]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/cstore.rs
Rollup merge of #41826 - GuillaumeGomez:add-markdown-content, r=frewsxcv
[rust.git] / src / librustc / middle / cstore.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
12 // file at the top-level directory of this distribution and at
13 // http://rust-lang.org/COPYRIGHT.
14 //
15 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
16 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
17 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
18 // option. This file may not be copied, modified, or distributed
19 // except according to those terms.
20
21 // the rustc crate store interface. This also includes types that
22 // are *mostly* used as a part of that interface, but these should
23 // probably get a better home if someone can find one.
24
25 use hir::def;
26 use dep_graph::DepNode;
27 use hir::def_id::{CrateNum, DefId, DefIndex};
28 use hir::map as hir_map;
29 use hir::map::definitions::{Definitions, DefKey, DisambiguatedDefPathData};
30 use hir::svh::Svh;
31 use ich;
32 use middle::lang_items;
33 use ty::{self, TyCtxt};
34 use session::Session;
35 use session::search_paths::PathKind;
36 use util::nodemap::{NodeSet, DefIdMap};
37
38 use std::any::Any;
39 use std::path::PathBuf;
40 use std::rc::Rc;
41 use syntax::ast;
42 use syntax::ext::base::SyntaxExtension;
43 use syntax::symbol::Symbol;
44 use syntax_pos::Span;
45 use rustc_back::target::Target;
46 use hir;
47 use rustc_back::PanicStrategy;
48
49 pub use self::NativeLibraryKind::*;
50
51 // lonely orphan structs and enums looking for a better home
52
53 #[derive(Clone, Debug)]
54 pub struct LinkMeta {
55     pub crate_hash: Svh,
56 }
57
58 // Where a crate came from on the local filesystem. One of these three options
59 // must be non-None.
60 #[derive(PartialEq, Clone, Debug)]
61 pub struct CrateSource {
62     pub dylib: Option<(PathBuf, PathKind)>,
63     pub rlib: Option<(PathBuf, PathKind)>,
64     pub rmeta: Option<(PathBuf, PathKind)>,
65 }
66
67 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
68 pub enum DepKind {
69     /// A dependency that is only used for its macros, none of which are visible from other crates.
70     /// These are included in the metadata only as placeholders and are ignored when decoding.
71     UnexportedMacrosOnly,
72     /// A dependency that is only used for its macros.
73     MacrosOnly,
74     /// A dependency that is always injected into the dependency list and so
75     /// doesn't need to be linked to an rlib, e.g. the injected allocator.
76     Implicit,
77     /// A dependency that is required by an rlib version of this crate.
78     /// Ordinary `extern crate`s result in `Explicit` dependencies.
79     Explicit,
80 }
81
82 impl DepKind {
83     pub fn macros_only(self) -> bool {
84         match self {
85             DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true,
86             DepKind::Implicit | DepKind::Explicit => false,
87         }
88     }
89 }
90
91 #[derive(PartialEq, Clone, Debug)]
92 pub enum LibSource {
93     Some(PathBuf),
94     MetadataOnly,
95     None,
96 }
97
98 impl LibSource {
99     pub fn is_some(&self) -> bool {
100         if let LibSource::Some(_) = *self {
101             true
102         } else {
103             false
104         }
105     }
106
107     pub fn option(&self) -> Option<PathBuf> {
108         match *self {
109             LibSource::Some(ref p) => Some(p.clone()),
110             LibSource::MetadataOnly | LibSource::None => None,
111         }
112     }
113 }
114
115 #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
116 pub enum LinkagePreference {
117     RequireDynamic,
118     RequireStatic,
119 }
120
121 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
122 pub enum NativeLibraryKind {
123     NativeStatic,    // native static library (.a archive)
124     NativeStaticNobundle, // native static library, which doesn't get bundled into .rlibs
125     NativeFramework, // macOS-specific
126     NativeUnknown,   // default way to specify a dynamic library
127 }
128
129 #[derive(Clone, Hash, RustcEncodable, RustcDecodable)]
130 pub struct NativeLibrary {
131     pub kind: NativeLibraryKind,
132     pub name: Symbol,
133     pub cfg: Option<ast::MetaItem>,
134     pub foreign_items: Vec<DefIndex>,
135 }
136
137 pub enum LoadedMacro {
138     MacroDef(ast::Item),
139     ProcMacro(Rc<SyntaxExtension>),
140 }
141
142 #[derive(Copy, Clone, Debug)]
143 pub struct ExternCrate {
144     /// def_id of an `extern crate` in the current crate that caused
145     /// this crate to be loaded; note that there could be multiple
146     /// such ids
147     pub def_id: DefId,
148
149     /// span of the extern crate that caused this to be loaded
150     pub span: Span,
151
152     /// If true, then this crate is the crate named by the extern
153     /// crate referenced above. If false, then this crate is a dep
154     /// of the crate.
155     pub direct: bool,
156
157     /// Number of links to reach the extern crate `def_id`
158     /// declaration; used to select the extern crate with the shortest
159     /// path
160     pub path_len: usize,
161 }
162
163 pub struct EncodedMetadata {
164     pub raw_data: Vec<u8>,
165     pub hashes: EncodedMetadataHashes,
166 }
167
168 impl EncodedMetadata {
169     pub fn new() -> EncodedMetadata {
170         EncodedMetadata {
171             raw_data: Vec::new(),
172             hashes: EncodedMetadataHashes::new(),
173         }
174     }
175 }
176
177 /// The hash for some metadata that (when saving) will be exported
178 /// from this crate, or which (when importing) was exported by an
179 /// upstream crate.
180 #[derive(Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
181 pub struct EncodedMetadataHash {
182     pub def_index: DefIndex,
183     pub hash: ich::Fingerprint,
184 }
185
186 /// The hash for some metadata that (when saving) will be exported
187 /// from this crate, or which (when importing) was exported by an
188 /// upstream crate.
189 #[derive(Debug, RustcEncodable, RustcDecodable, Clone)]
190 pub struct EncodedMetadataHashes {
191     pub entry_hashes: Vec<EncodedMetadataHash>,
192     pub global_hashes: Vec<(DepNode<()>, ich::Fingerprint)>,
193 }
194
195 impl EncodedMetadataHashes {
196     pub fn new() -> EncodedMetadataHashes {
197         EncodedMetadataHashes {
198             entry_hashes: Vec::new(),
199             global_hashes: Vec::new(),
200         }
201     }
202 }
203
204 /// A store of Rust crates, through with their metadata
205 /// can be accessed.
206 pub trait CrateStore {
207     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any>;
208
209     // item info
210     fn visibility(&self, def: DefId) -> ty::Visibility;
211     fn visible_parent_map<'a>(&'a self) -> ::std::cell::Ref<'a, DefIdMap<DefId>>;
212     fn item_generics_cloned(&self, def: DefId) -> ty::Generics;
213
214     // trait info
215     fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId>;
216
217     // impl info
218     fn impl_defaultness(&self, def: DefId) -> hir::Defaultness;
219
220     // trait/impl-item info
221     fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem;
222
223     // flags
224     fn is_const_fn(&self, did: DefId) -> bool;
225     fn is_default_impl(&self, impl_did: DefId) -> bool;
226     fn is_dllimport_foreign_item(&self, def: DefId) -> bool;
227     fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool;
228
229     // crate metadata
230     fn dylib_dependency_formats(&self, cnum: CrateNum)
231                                     -> Vec<(CrateNum, LinkagePreference)>;
232     fn dep_kind(&self, cnum: CrateNum) -> DepKind;
233     fn export_macros(&self, cnum: CrateNum);
234     fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>;
235     fn missing_lang_items(&self, cnum: CrateNum) -> Vec<lang_items::LangItem>;
236     fn is_allocator(&self, cnum: CrateNum) -> bool;
237     fn is_panic_runtime(&self, cnum: CrateNum) -> bool;
238     fn is_compiler_builtins(&self, cnum: CrateNum) -> bool;
239     fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool;
240     fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy;
241     fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate>;
242     /// The name of the crate as it is referred to in source code of the current
243     /// crate.
244     fn crate_name(&self, cnum: CrateNum) -> Symbol;
245     /// The name of the crate as it is stored in the crate's metadata.
246     fn original_crate_name(&self, cnum: CrateNum) -> Symbol;
247     fn crate_hash(&self, cnum: CrateNum) -> Svh;
248     fn crate_disambiguator(&self, cnum: CrateNum) -> Symbol;
249     fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>;
250     fn derive_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>;
251     fn native_libraries(&self, cnum: CrateNum) -> Vec<NativeLibrary>;
252     fn exported_symbols(&self, cnum: CrateNum) -> Vec<DefId>;
253     fn is_no_builtins(&self, cnum: CrateNum) -> bool;
254
255     // resolve
256     fn retrace_path(&self,
257                     cnum: CrateNum,
258                     path_data: &[DisambiguatedDefPathData])
259                     -> Option<DefId>;
260     fn def_key(&self, def: DefId) -> DefKey;
261     fn def_path(&self, def: DefId) -> hir_map::DefPath;
262     fn def_path_hash(&self, def: DefId) -> u64;
263     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>;
264     fn item_children(&self, did: DefId) -> Vec<def::Export>;
265     fn load_macro(&self, did: DefId, sess: &Session) -> LoadedMacro;
266
267     // misc. metadata
268     fn item_body<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, def: DefId)
269                            -> &'tcx hir::Body;
270
271     // This is basically a 1-based range of ints, which is a little
272     // silly - I may fix that.
273     fn crates(&self) -> Vec<CrateNum>;
274     fn used_libraries(&self) -> Vec<NativeLibrary>;
275     fn used_link_args(&self) -> Vec<String>;
276
277     // utility functions
278     fn metadata_filename(&self) -> &str;
279     fn metadata_section_name(&self, target: &Target) -> &str;
280     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>;
281     fn used_crate_source(&self, cnum: CrateNum) -> CrateSource;
282     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
283     fn encode_metadata<'a, 'tcx>(&self,
284                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
285                                  link_meta: &LinkMeta,
286                                  reachable: &NodeSet)
287                                  -> EncodedMetadata;
288     fn metadata_encoding_version(&self) -> &[u8];
289 }
290
291 // FIXME: find a better place for this?
292 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
293     let mut err_count = 0;
294     {
295         let mut say = |s: &str| {
296             match (sp, sess) {
297                 (_, None) => bug!("{}", s),
298                 (Some(sp), Some(sess)) => sess.span_err(sp, s),
299                 (None, Some(sess)) => sess.err(s),
300             }
301             err_count += 1;
302         };
303         if s.is_empty() {
304             say("crate name must not be empty");
305         }
306         for c in s.chars() {
307             if c.is_alphanumeric() { continue }
308             if c == '_'  { continue }
309             say(&format!("invalid character `{}` in crate name: `{}`", c, s));
310         }
311     }
312
313     if err_count > 0 {
314         sess.unwrap().abort_if_errors();
315     }
316 }
317
318 /// A dummy crate store that does not support any non-local crates,
319 /// for test purposes.
320 pub struct DummyCrateStore;
321
322 #[allow(unused_variables)]
323 impl CrateStore for DummyCrateStore {
324     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any>
325         { bug!("crate_data_as_rc_any") }
326     // item info
327     fn visibility(&self, def: DefId) -> ty::Visibility { bug!("visibility") }
328     fn visible_parent_map<'a>(&'a self) -> ::std::cell::Ref<'a, DefIdMap<DefId>> {
329         bug!("visible_parent_map")
330     }
331     fn item_generics_cloned(&self, def: DefId) -> ty::Generics
332         { bug!("item_generics_cloned") }
333
334     // trait info
335     fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId> { vec![] }
336
337     // impl info
338     fn impl_defaultness(&self, def: DefId) -> hir::Defaultness { bug!("impl_defaultness") }
339
340     // trait/impl-item info
341     fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem
342         { bug!("associated_item_cloned") }
343
344     // flags
345     fn is_const_fn(&self, did: DefId) -> bool { bug!("is_const_fn") }
346     fn is_default_impl(&self, impl_did: DefId) -> bool { bug!("is_default_impl") }
347     fn is_dllimport_foreign_item(&self, id: DefId) -> bool { false }
348     fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool { false }
349
350     // crate metadata
351     fn dylib_dependency_formats(&self, cnum: CrateNum)
352                                     -> Vec<(CrateNum, LinkagePreference)>
353         { bug!("dylib_dependency_formats") }
354     fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
355         { bug!("lang_items") }
356     fn missing_lang_items(&self, cnum: CrateNum) -> Vec<lang_items::LangItem>
357         { bug!("missing_lang_items") }
358     fn dep_kind(&self, cnum: CrateNum) -> DepKind { bug!("is_explicitly_linked") }
359     fn export_macros(&self, cnum: CrateNum) { bug!("export_macros") }
360     fn is_allocator(&self, cnum: CrateNum) -> bool { bug!("is_allocator") }
361     fn is_panic_runtime(&self, cnum: CrateNum) -> bool { bug!("is_panic_runtime") }
362     fn is_compiler_builtins(&self, cnum: CrateNum) -> bool { bug!("is_compiler_builtins") }
363     fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool { bug!("is_sanitizer_runtime") }
364     fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy {
365         bug!("panic_strategy")
366     }
367     fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate> { bug!("extern_crate") }
368     fn crate_name(&self, cnum: CrateNum) -> Symbol { bug!("crate_name") }
369     fn original_crate_name(&self, cnum: CrateNum) -> Symbol {
370         bug!("original_crate_name")
371     }
372     fn crate_hash(&self, cnum: CrateNum) -> Svh { bug!("crate_hash") }
373     fn crate_disambiguator(&self, cnum: CrateNum)
374                            -> Symbol { bug!("crate_disambiguator") }
375     fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
376         { bug!("plugin_registrar_fn") }
377     fn derive_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
378         { bug!("derive_registrar_fn") }
379     fn native_libraries(&self, cnum: CrateNum) -> Vec<NativeLibrary>
380         { bug!("native_libraries") }
381     fn exported_symbols(&self, cnum: CrateNum) -> Vec<DefId> { bug!("exported_symbols") }
382     fn is_no_builtins(&self, cnum: CrateNum) -> bool { bug!("is_no_builtins") }
383
384     // resolve
385     fn retrace_path(&self,
386                     cnum: CrateNum,
387                     path_data: &[DisambiguatedDefPathData])
388                     -> Option<DefId> {
389         None
390     }
391
392     fn def_key(&self, def: DefId) -> DefKey { bug!("def_key") }
393     fn def_path(&self, def: DefId) -> hir_map::DefPath {
394         bug!("relative_def_path")
395     }
396     fn def_path_hash(&self, def: DefId) -> u64 {
397         bug!("wa")
398     }
399     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name> { bug!("struct_field_names") }
400     fn item_children(&self, did: DefId) -> Vec<def::Export> { bug!("item_children") }
401     fn load_macro(&self, did: DefId, sess: &Session) -> LoadedMacro { bug!("load_macro") }
402
403     // misc. metadata
404     fn item_body<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, def: DefId)
405                            -> &'tcx hir::Body {
406         bug!("item_body")
407     }
408
409     // This is basically a 1-based range of ints, which is a little
410     // silly - I may fix that.
411     fn crates(&self) -> Vec<CrateNum> { vec![] }
412     fn used_libraries(&self) -> Vec<NativeLibrary> { vec![] }
413     fn used_link_args(&self) -> Vec<String> { vec![] }
414
415     // utility functions
416     fn metadata_filename(&self) -> &str { bug!("metadata_filename") }
417     fn metadata_section_name(&self, target: &Target) -> &str { bug!("metadata_section_name") }
418     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>
419         { vec![] }
420     fn used_crate_source(&self, cnum: CrateNum) -> CrateSource { bug!("used_crate_source") }
421     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum> { None }
422     fn encode_metadata<'a, 'tcx>(&self,
423                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
424                                  link_meta: &LinkMeta,
425                                  reachable: &NodeSet)
426                                  -> EncodedMetadata {
427         bug!("encode_metadata")
428     }
429     fn metadata_encoding_version(&self) -> &[u8] { bug!("metadata_encoding_version") }
430 }
431
432 pub trait CrateLoader {
433     fn process_item(&mut self, item: &ast::Item, defs: &Definitions);
434     fn postprocess(&mut self, krate: &ast::Crate);
435 }