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