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