]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/cstore.rs
Fix checking for missing stability annotations
[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                             DefPathTable};
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::{Path, PathBuf};
40 use std::rc::Rc;
41 use owning_ref::ErasedBoxRef;
42 use syntax::ast;
43 use syntax::ext::base::SyntaxExtension;
44 use syntax::symbol::Symbol;
45 use syntax_pos::Span;
46 use rustc_back::target::Target;
47 use hir;
48 use rustc_back::PanicStrategy;
49
50 pub use self::NativeLibraryKind::*;
51
52 // lonely orphan structs and enums looking for a better home
53
54 #[derive(Clone, Debug)]
55 pub struct LinkMeta {
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 pub struct EncodedMetadata {
165     pub raw_data: Vec<u8>,
166     pub hashes: EncodedMetadataHashes,
167 }
168
169 impl EncodedMetadata {
170     pub fn new() -> EncodedMetadata {
171         EncodedMetadata {
172             raw_data: Vec::new(),
173             hashes: EncodedMetadataHashes::new(),
174         }
175     }
176 }
177
178 /// The hash for some metadata that (when saving) will be exported
179 /// from this crate, or which (when importing) was exported by an
180 /// upstream crate.
181 #[derive(Debug, RustcEncodable, RustcDecodable, Copy, Clone)]
182 pub struct EncodedMetadataHash {
183     pub def_index: DefIndex,
184     pub hash: ich::Fingerprint,
185 }
186
187 /// The hash for some metadata that (when saving) will be exported
188 /// from this crate, or which (when importing) was exported by an
189 /// upstream crate.
190 #[derive(Debug, RustcEncodable, RustcDecodable, Clone)]
191 pub struct EncodedMetadataHashes {
192     // Stable content hashes for things in crate metadata, indexed by DefIndex.
193     pub hashes: Vec<EncodedMetadataHash>,
194 }
195
196 impl EncodedMetadataHashes {
197     pub fn new() -> EncodedMetadataHashes {
198         EncodedMetadataHashes {
199             hashes: Vec::new(),
200         }
201     }
202 }
203
204 /// The backend's way to give the crate store access to the metadata in a library.
205 /// Note that it returns the raw metadata bytes stored in the library file, whether
206 /// it is compressed, uncompressed, some weird mix, etc.
207 /// rmeta files are backend independent and not handled here.
208 ///
209 /// At the time of this writing, there is only one backend and one way to store
210 /// metadata in library -- this trait just serves to decouple rustc_metadata from
211 /// the archive reader, which depends on LLVM.
212 pub trait MetadataLoader {
213     fn get_rlib_metadata(&self,
214                          target: &Target,
215                          filename: &Path)
216                          -> Result<ErasedBoxRef<[u8]>, String>;
217     fn get_dylib_metadata(&self,
218                           target: &Target,
219                           filename: &Path)
220                           -> Result<ErasedBoxRef<[u8]>, String>;
221 }
222
223 /// A store of Rust crates, through with their metadata
224 /// can be accessed.
225 pub trait CrateStore {
226     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any>;
227
228     // access to the metadata loader
229     fn metadata_loader(&self) -> &MetadataLoader;
230
231     // item info
232     fn visibility(&self, def: DefId) -> ty::Visibility;
233     fn visible_parent_map<'a>(&'a self, sess: &Session) -> ::std::cell::Ref<'a, DefIdMap<DefId>>;
234     fn item_generics_cloned(&self, def: DefId) -> ty::Generics;
235
236     // trait info
237     fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId>;
238
239     // impl info
240     fn impl_defaultness(&self, def: DefId) -> hir::Defaultness;
241
242     // trait/impl-item info
243     fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem;
244
245     // flags
246     fn is_dllimport_foreign_item(&self, def: DefId) -> bool;
247     fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool;
248
249     // crate metadata
250     fn dep_kind(&self, cnum: CrateNum) -> DepKind;
251     fn export_macros(&self, cnum: CrateNum);
252     fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>;
253     fn missing_lang_items(&self, cnum: CrateNum) -> Vec<lang_items::LangItem>;
254     fn is_compiler_builtins(&self, cnum: CrateNum) -> bool;
255     fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool;
256     fn is_profiler_runtime(&self, cnum: CrateNum) -> bool;
257     fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy;
258     /// The name of the crate as it is referred to in source code of the current
259     /// crate.
260     fn crate_name(&self, cnum: CrateNum) -> Symbol;
261     /// The name of the crate as it is stored in the crate's metadata.
262     fn original_crate_name(&self, cnum: CrateNum) -> Symbol;
263     fn crate_hash(&self, cnum: CrateNum) -> Svh;
264     fn crate_disambiguator(&self, cnum: CrateNum) -> Symbol;
265     fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>;
266     fn derive_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>;
267     fn native_libraries(&self, cnum: CrateNum) -> Vec<NativeLibrary>;
268     fn exported_symbols(&self, cnum: CrateNum) -> Vec<DefId>;
269     fn is_no_builtins(&self, cnum: CrateNum) -> bool;
270
271     // resolve
272     fn retrace_path(&self,
273                     cnum: CrateNum,
274                     path_data: &[DisambiguatedDefPathData])
275                     -> Option<DefId>;
276     fn def_key(&self, def: DefId) -> DefKey;
277     fn def_path(&self, def: DefId) -> hir_map::DefPath;
278     fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash;
279     fn def_path_table(&self, cnum: CrateNum) -> Rc<DefPathTable>;
280     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>;
281     fn item_children(&self, did: DefId, sess: &Session) -> Vec<def::Export>;
282     fn load_macro(&self, did: DefId, sess: &Session) -> LoadedMacro;
283
284     // misc. metadata
285     fn item_body<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, def: DefId)
286                            -> &'tcx hir::Body;
287
288     // This is basically a 1-based range of ints, which is a little
289     // silly - I may fix that.
290     fn crates(&self) -> Vec<CrateNum>;
291     fn used_libraries(&self) -> Vec<NativeLibrary>;
292     fn used_link_args(&self) -> Vec<String>;
293
294     // utility functions
295     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>;
296     fn used_crate_source(&self, cnum: CrateNum) -> CrateSource;
297     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
298     fn encode_metadata<'a, 'tcx>(&self,
299                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
300                                  link_meta: &LinkMeta,
301                                  reachable: &NodeSet)
302                                  -> EncodedMetadata;
303     fn metadata_encoding_version(&self) -> &[u8];
304 }
305
306 // FIXME: find a better place for this?
307 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
308     let mut err_count = 0;
309     {
310         let mut say = |s: &str| {
311             match (sp, sess) {
312                 (_, None) => bug!("{}", s),
313                 (Some(sp), Some(sess)) => sess.span_err(sp, s),
314                 (None, Some(sess)) => sess.err(s),
315             }
316             err_count += 1;
317         };
318         if s.is_empty() {
319             say("crate name must not be empty");
320         }
321         for c in s.chars() {
322             if c.is_alphanumeric() { continue }
323             if c == '_'  { continue }
324             say(&format!("invalid character `{}` in crate name: `{}`", c, s));
325         }
326     }
327
328     if err_count > 0 {
329         sess.unwrap().abort_if_errors();
330     }
331 }
332
333 /// A dummy crate store that does not support any non-local crates,
334 /// for test purposes.
335 pub struct DummyCrateStore;
336
337 #[allow(unused_variables)]
338 impl CrateStore for DummyCrateStore {
339     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Rc<Any>
340         { bug!("crate_data_as_rc_any") }
341     // item info
342     fn visibility(&self, def: DefId) -> ty::Visibility { bug!("visibility") }
343     fn visible_parent_map<'a>(&'a self, session: &Session)
344         -> ::std::cell::Ref<'a, DefIdMap<DefId>>
345     {
346         bug!("visible_parent_map")
347     }
348     fn item_generics_cloned(&self, def: DefId) -> ty::Generics
349         { bug!("item_generics_cloned") }
350
351     // trait info
352     fn implementations_of_trait(&self, filter: Option<DefId>) -> Vec<DefId> { vec![] }
353
354     // impl info
355     fn impl_defaultness(&self, def: DefId) -> hir::Defaultness { bug!("impl_defaultness") }
356
357     // trait/impl-item info
358     fn associated_item_cloned(&self, def: DefId) -> ty::AssociatedItem
359         { bug!("associated_item_cloned") }
360
361     // flags
362     fn is_dllimport_foreign_item(&self, id: DefId) -> bool { false }
363     fn is_statically_included_foreign_item(&self, def_id: DefId) -> bool { false }
364
365     // crate metadata
366     fn lang_items(&self, cnum: CrateNum) -> Vec<(DefIndex, usize)>
367         { bug!("lang_items") }
368     fn missing_lang_items(&self, cnum: CrateNum) -> Vec<lang_items::LangItem>
369         { bug!("missing_lang_items") }
370     fn dep_kind(&self, cnum: CrateNum) -> DepKind { bug!("is_explicitly_linked") }
371     fn export_macros(&self, cnum: CrateNum) { bug!("export_macros") }
372     fn is_compiler_builtins(&self, cnum: CrateNum) -> bool { bug!("is_compiler_builtins") }
373     fn is_profiler_runtime(&self, cnum: CrateNum) -> bool { bug!("is_profiler_runtime") }
374     fn is_sanitizer_runtime(&self, cnum: CrateNum) -> bool { bug!("is_sanitizer_runtime") }
375     fn panic_strategy(&self, cnum: CrateNum) -> PanicStrategy {
376         bug!("panic_strategy")
377     }
378     fn crate_name(&self, cnum: CrateNum) -> Symbol { bug!("crate_name") }
379     fn original_crate_name(&self, cnum: CrateNum) -> Symbol {
380         bug!("original_crate_name")
381     }
382     fn crate_hash(&self, cnum: CrateNum) -> Svh { bug!("crate_hash") }
383     fn crate_disambiguator(&self, cnum: CrateNum)
384                            -> Symbol { bug!("crate_disambiguator") }
385     fn plugin_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
386         { bug!("plugin_registrar_fn") }
387     fn derive_registrar_fn(&self, cnum: CrateNum) -> Option<DefId>
388         { bug!("derive_registrar_fn") }
389     fn native_libraries(&self, cnum: CrateNum) -> Vec<NativeLibrary>
390         { bug!("native_libraries") }
391     fn exported_symbols(&self, cnum: CrateNum) -> Vec<DefId> { bug!("exported_symbols") }
392     fn is_no_builtins(&self, cnum: CrateNum) -> bool { bug!("is_no_builtins") }
393
394     // resolve
395     fn retrace_path(&self,
396                     cnum: CrateNum,
397                     path_data: &[DisambiguatedDefPathData])
398                     -> Option<DefId> {
399         None
400     }
401
402     fn def_key(&self, def: DefId) -> DefKey { bug!("def_key") }
403     fn def_path(&self, def: DefId) -> hir_map::DefPath {
404         bug!("relative_def_path")
405     }
406     fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash {
407         bug!("def_path_hash")
408     }
409     fn def_path_table(&self, cnum: CrateNum) -> Rc<DefPathTable> {
410         bug!("def_path_table")
411     }
412     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name> { bug!("struct_field_names") }
413     fn item_children(&self, did: DefId, sess: &Session) -> Vec<def::Export> {
414         bug!("item_children")
415     }
416     fn load_macro(&self, did: DefId, sess: &Session) -> LoadedMacro { bug!("load_macro") }
417
418     // misc. metadata
419     fn item_body<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, def: DefId)
420                            -> &'tcx hir::Body {
421         bug!("item_body")
422     }
423
424     // This is basically a 1-based range of ints, which is a little
425     // silly - I may fix that.
426     fn crates(&self) -> Vec<CrateNum> { vec![] }
427     fn used_libraries(&self) -> Vec<NativeLibrary> { vec![] }
428     fn used_link_args(&self) -> Vec<String> { vec![] }
429
430     // utility functions
431     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(CrateNum, LibSource)>
432         { vec![] }
433     fn used_crate_source(&self, cnum: CrateNum) -> CrateSource { bug!("used_crate_source") }
434     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum> { None }
435     fn encode_metadata<'a, 'tcx>(&self,
436                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
437                                  link_meta: &LinkMeta,
438                                  reachable: &NodeSet)
439                                  -> EncodedMetadata {
440         bug!("encode_metadata")
441     }
442     fn metadata_encoding_version(&self) -> &[u8] { bug!("metadata_encoding_version") }
443
444     // access to the metadata loader
445     fn metadata_loader(&self) -> &MetadataLoader { bug!("metadata_loader") }
446 }
447
448 pub trait CrateLoader {
449     fn process_item(&mut self, item: &ast::Item, defs: &Definitions);
450     fn postprocess(&mut self, krate: &ast::Crate);
451 }