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