]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/cstore.rs
Auto merge of #41488 - estebank:closure-args, r=arielb1
[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::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_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: Vec<EncodedMetadataHash>,
166 }
167
168 /// The hash for some metadata that (when saving) will be exported
169 /// from this crate, or which (when importing) was exported by an
170 /// upstream crate.
171 #[derive(Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
172 pub struct EncodedMetadataHash {
173     pub def_index: DefIndex,
174     pub hash: ich::Fingerprint,
175 }
176
177 /// A store of Rust crates, through with their metadata
178 /// can be accessed.
179 pub trait CrateStore {
180     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any>;
181
182     // item info
183     fn stability(&self, def: DefId) -> Option<attr::Stability>;
184     fn deprecation(&self, def: DefId) -> Option<attr::Deprecation>;
185     fn visibility(&self, def: DefId) -> ty::Visibility;
186     fn visible_parent_map<'a>(&'a self) -> ::std::cell::Ref<'a, DefIdMap<DefId>>;
187     fn item_generics_cloned(&self, def: DefId) -> ty::Generics;
188     fn item_attrs(&self, def_id: DefId) -> Rc<[ast::Attribute]>;
189     fn fn_arg_names(&self, did: DefId) -> Vec<ast::Name>;
190
191     // trait info
192     fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId>;
193
194     // impl info
195     fn impl_defaultness(&self, def: DefId) -> hir::Defaultness;
196     fn impl_parent(&self, impl_def_id: DefId) -> Option<DefId>;
197
198     // trait/impl-item info
199     fn trait_of_item(&self, def_id: DefId) -> Option<DefId>;
200     fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem;
201
202     // flags
203     fn is_const_fn(&self, did: DefId) -> bool;
204     fn is_default_impl(&self, impl_did: DefId) -> bool;
205     fn is_foreign_item(&self, did: DefId) -> bool;
206     fn is_dllimport_foreign_item(&self, def: DefId) -> bool;
207     fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool;
208     fn is_exported_symbol(&self, def_id: DefId) -> bool;
209
210     // crate metadata
211     fn dylib_dependency_formats(&self, cnum: CrateNum)
212                                     -> Vec<(CrateNum, LinkagePreference)>;
213     fn dep_kind(&self, cnum: CrateNum) -> DepKind;
214     fn export_macros(&self, cnum: CrateNum);
215     fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>;
216     fn missing_lang_items(&self, cnum: CrateNum) -> Vec<lang_items::LangItem>;
217     fn is_staged_api(&self, cnum: CrateNum) -> bool;
218     fn is_allocator(&self, cnum: CrateNum) -> bool;
219     fn is_panic_runtime(&self, cnum: CrateNum) -> bool;
220     fn is_compiler_builtins(&self, cnum: CrateNum) -> bool;
221     fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool;
222     fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy;
223     fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate>;
224     /// The name of the crate as it is referred to in source code of the current
225     /// crate.
226     fn crate_name(&self, cnum: CrateNum) -> Symbol;
227     /// The name of the crate as it is stored in the crate's metadata.
228     fn original_crate_name(&self, cnum: CrateNum) -> Symbol;
229     fn crate_hash(&self, cnum: CrateNum) -> Svh;
230     fn crate_disambiguator(&self, cnum: CrateNum) -> Symbol;
231     fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>;
232     fn derive_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>;
233     fn native_libraries(&self, cnum: CrateNum) -> Vec<NativeLibrary>;
234     fn exported_symbols(&self, cnum: CrateNum) -> Vec<DefId>;
235     fn is_no_builtins(&self, cnum: CrateNum) -> bool;
236
237     // resolve
238     fn retrace_path(&self,
239                     cnum: CrateNum,
240                     path_data: &[DisambiguatedDefPathData])
241                     -> Option<DefId>;
242     fn def_key(&self, def: DefId) -> DefKey;
243     fn def_path(&self, def: DefId) -> hir_map::DefPath;
244     fn def_path_hash(&self, def: DefId) -> u64;
245     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>;
246     fn item_children(&self, did: DefId) -> Vec<def::Export>;
247     fn load_macro(&self, did: DefId, sess: &Session) -> LoadedMacro;
248
249     // misc. metadata
250     fn item_body<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, def: DefId)
251                            -> &'tcx hir::Body;
252
253     // This is basically a 1-based range of ints, which is a little
254     // silly - I may fix that.
255     fn crates(&self) -> Vec<CrateNum>;
256     fn used_libraries(&self) -> Vec<NativeLibrary>;
257     fn used_link_args(&self) -> Vec<String>;
258
259     // utility functions
260     fn metadata_filename(&self) -> &str;
261     fn metadata_section_name(&self, target: &Target) -> &str;
262     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>;
263     fn used_crate_source(&self, cnum: CrateNum) -> CrateSource;
264     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
265     fn encode_metadata<'a, 'tcx>(&self,
266                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
267                                  link_meta: &LinkMeta,
268                                  reachable: &NodeSet)
269                                  -> EncodedMetadata;
270     fn metadata_encoding_version(&self) -> &[u8];
271 }
272
273 // FIXME: find a better place for this?
274 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
275     let mut err_count = 0;
276     {
277         let mut say = |s: &str| {
278             match (sp, sess) {
279                 (_, None) => bug!("{}", s),
280                 (Some(sp), Some(sess)) => sess.span_err(sp, s),
281                 (None, Some(sess)) => sess.err(s),
282             }
283             err_count += 1;
284         };
285         if s.is_empty() {
286             say("crate name must not be empty");
287         }
288         for c in s.chars() {
289             if c.is_alphanumeric() { continue }
290             if c == '_'  { continue }
291             say(&format!("invalid character `{}` in crate name: `{}`", c, s));
292         }
293     }
294
295     if err_count > 0 {
296         sess.unwrap().abort_if_errors();
297     }
298 }
299
300 /// A dummy crate store that does not support any non-local crates,
301 /// for test purposes.
302 pub struct DummyCrateStore;
303
304 #[allow(unused_variables)]
305 impl CrateStore for DummyCrateStore {
306     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any>
307         { bug!("crate_data_as_rc_any") }
308     // item info
309     fn stability(&self, def: DefId) -> Option<attr::Stability> { bug!("stability") }
310     fn deprecation(&self, def: DefId) -> Option<attr::Deprecation> { bug!("deprecation") }
311     fn visibility(&self, def: DefId) -> ty::Visibility { bug!("visibility") }
312     fn visible_parent_map<'a>(&'a self) -> ::std::cell::Ref<'a, DefIdMap<DefId>> {
313         bug!("visible_parent_map")
314     }
315     fn item_generics_cloned(&self, def: DefId) -> ty::Generics
316         { bug!("item_generics_cloned") }
317     fn item_attrs(&self, def_id: DefId) -> Rc<[ast::Attribute]> { bug!("item_attrs") }
318     fn fn_arg_names(&self, did: DefId) -> Vec<ast::Name> { bug!("fn_arg_names") }
319
320     // trait info
321     fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId> { vec![] }
322
323     // impl info
324     fn impl_defaultness(&self, def: DefId) -> hir::Defaultness { bug!("impl_defaultness") }
325     fn impl_parent(&self, def: DefId) -> Option<DefId> { bug!("impl_parent") }
326
327     // trait/impl-item info
328     fn trait_of_item(&self, def_id: DefId) -> Option<DefId> { bug!("trait_of_item") }
329     fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem
330         { bug!("associated_item_cloned") }
331
332     // flags
333     fn is_const_fn(&self, did: DefId) -> bool { bug!("is_const_fn") }
334     fn is_default_impl(&self, impl_did: DefId) -> bool { bug!("is_default_impl") }
335     fn is_foreign_item(&self, did: DefId) -> bool { bug!("is_foreign_item") }
336     fn is_dllimport_foreign_item(&self, id: DefId) -> bool { false }
337     fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool { false }
338     fn is_exported_symbol(&self, def_id: DefId) -> bool { false }
339
340     // crate metadata
341     fn dylib_dependency_formats(&self, cnum: CrateNum)
342                                     -> Vec<(CrateNum, LinkagePreference)>
343         { bug!("dylib_dependency_formats") }
344     fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
345         { bug!("lang_items") }
346     fn missing_lang_items(&self, cnum: CrateNum) -> Vec<lang_items::LangItem>
347         { bug!("missing_lang_items") }
348     fn is_staged_api(&self, cnum: CrateNum) -> bool { bug!("is_staged_api") }
349     fn dep_kind(&self, cnum: CrateNum) -> DepKind { bug!("is_explicitly_linked") }
350     fn export_macros(&self, cnum: CrateNum) { bug!("export_macros") }
351     fn is_allocator(&self, cnum: CrateNum) -> bool { bug!("is_allocator") }
352     fn is_panic_runtime(&self, cnum: CrateNum) -> bool { bug!("is_panic_runtime") }
353     fn is_compiler_builtins(&self, cnum: CrateNum) -> bool { bug!("is_compiler_builtins") }
354     fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool { bug!("is_sanitizer_runtime") }
355     fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy {
356         bug!("panic_strategy")
357     }
358     fn extern_crate(&self, cnum: CrateNum) -> Option<ExternCrate> { bug!("extern_crate") }
359     fn crate_name(&self, cnum: CrateNum) -> Symbol { bug!("crate_name") }
360     fn original_crate_name(&self, cnum: CrateNum) -> Symbol {
361         bug!("original_crate_name")
362     }
363     fn crate_hash(&self, cnum: CrateNum) -> Svh { bug!("crate_hash") }
364     fn crate_disambiguator(&self, cnum: CrateNum)
365                            -> Symbol { bug!("crate_disambiguator") }
366     fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
367         { bug!("plugin_registrar_fn") }
368     fn derive_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
369         { bug!("derive_registrar_fn") }
370     fn native_libraries(&self, cnum: CrateNum) -> Vec<NativeLibrary>
371         { bug!("native_libraries") }
372     fn exported_symbols(&self, cnum: CrateNum) -> Vec<DefId> { bug!("exported_symbols") }
373     fn is_no_builtins(&self, cnum: CrateNum) -> bool { bug!("is_no_builtins") }
374
375     // resolve
376     fn retrace_path(&self,
377                     cnum: CrateNum,
378                     path_data: &[DisambiguatedDefPathData])
379                     -> Option<DefId> {
380         None
381     }
382
383     fn def_key(&self, def: DefId) -> DefKey { bug!("def_key") }
384     fn def_path(&self, def: DefId) -> hir_map::DefPath {
385         bug!("relative_def_path")
386     }
387     fn def_path_hash(&self, def: DefId) -> u64 {
388         bug!("wa")
389     }
390     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name> { bug!("struct_field_names") }
391     fn item_children(&self, did: DefId) -> Vec<def::Export> { bug!("item_children") }
392     fn load_macro(&self, did: DefId, sess: &Session) -> LoadedMacro { bug!("load_macro") }
393
394     // misc. metadata
395     fn item_body<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, def: DefId)
396                            -> &'tcx hir::Body {
397         bug!("item_body")
398     }
399
400     // This is basically a 1-based range of ints, which is a little
401     // silly - I may fix that.
402     fn crates(&self) -> Vec<CrateNum> { vec![] }
403     fn used_libraries(&self) -> Vec<NativeLibrary> { vec![] }
404     fn used_link_args(&self) -> Vec<String> { vec![] }
405
406     // utility functions
407     fn metadata_filename(&self) -> &str { bug!("metadata_filename") }
408     fn metadata_section_name(&self, target: &Target) -> &str { bug!("metadata_section_name") }
409     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>
410         { vec![] }
411     fn used_crate_source(&self, cnum: CrateNum) -> CrateSource { bug!("used_crate_source") }
412     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum> { None }
413     fn encode_metadata<'a, 'tcx>(&self,
414                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
415                                  link_meta: &LinkMeta,
416                                  reachable: &NodeSet)
417                                  -> EncodedMetadata {
418         bug!("encode_metadata")
419     }
420     fn metadata_encoding_version(&self) -> &[u8] { bug!("metadata_encoding_version") }
421 }
422
423 pub trait CrateLoader {
424     fn process_item(&mut self, item: &ast::Item, defs: &Definitions);
425     fn postprocess(&mut self, krate: &ast::Crate);
426 }