]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/cstore.rs
Deny bare trait objects in in src/librustc
[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, LOCAL_CRATE};
27 use hir::map as hir_map;
28 use hir::map::definitions::{Definitions, DefKey, DefPathTable};
29 use hir::svh::Svh;
30 use ty::{self, TyCtxt};
31 use session::{Session, CrateDisambiguator};
32 use session::search_paths::PathKind;
33
34 use std::any::Any;
35 use std::path::{Path, PathBuf};
36 use syntax::ast;
37 use syntax::edition::Edition;
38 use syntax::ext::base::SyntaxExtension;
39 use syntax::symbol::Symbol;
40 use syntax_pos::Span;
41 use rustc_target::spec::Target;
42 use rustc_data_structures::sync::{self, MetadataRef, Lrc};
43
44 pub use self::NativeLibraryKind::*;
45
46 // lonely orphan structs and enums looking for a better home
47
48 #[derive(Clone, Debug, Copy)]
49 pub struct LinkMeta {
50     pub crate_hash: Svh,
51 }
52
53 /// Where a crate came from on the local filesystem. One of these three options
54 /// must be non-None.
55 #[derive(PartialEq, Clone, Debug)]
56 pub struct CrateSource {
57     pub dylib: Option<(PathBuf, PathKind)>,
58     pub rlib: Option<(PathBuf, PathKind)>,
59     pub rmeta: Option<(PathBuf, PathKind)>,
60 }
61
62 #[derive(RustcEncodable, RustcDecodable, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)]
63 pub enum DepKind {
64     /// A dependency that is only used for its macros, none of which are visible from other crates.
65     /// These are included in the metadata only as placeholders and are ignored when decoding.
66     UnexportedMacrosOnly,
67     /// A dependency that is only used for its macros.
68     MacrosOnly,
69     /// A dependency that is always injected into the dependency list and so
70     /// doesn't need to be linked to an rlib, e.g. the injected allocator.
71     Implicit,
72     /// A dependency that is required by an rlib version of this crate.
73     /// Ordinary `extern crate`s result in `Explicit` dependencies.
74     Explicit,
75 }
76
77 impl DepKind {
78     pub fn macros_only(self) -> bool {
79         match self {
80             DepKind::UnexportedMacrosOnly | DepKind::MacrosOnly => true,
81             DepKind::Implicit | DepKind::Explicit => false,
82         }
83     }
84 }
85
86 #[derive(PartialEq, Clone, Debug)]
87 pub enum LibSource {
88     Some(PathBuf),
89     MetadataOnly,
90     None,
91 }
92
93 impl LibSource {
94     pub fn is_some(&self) -> bool {
95         if let LibSource::Some(_) = *self {
96             true
97         } else {
98             false
99         }
100     }
101
102     pub fn option(&self) -> Option<PathBuf> {
103         match *self {
104             LibSource::Some(ref p) => Some(p.clone()),
105             LibSource::MetadataOnly | LibSource::None => None,
106         }
107     }
108 }
109
110 #[derive(Copy, Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
111 pub enum LinkagePreference {
112     RequireDynamic,
113     RequireStatic,
114 }
115
116 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
117 pub enum NativeLibraryKind {
118     /// native static library (.a archive)
119     NativeStatic,
120     /// native static library, which doesn't get bundled into .rlibs
121     NativeStaticNobundle,
122     /// macOS-specific
123     NativeFramework,
124     /// default way to specify a dynamic library
125     NativeUnknown,
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_module: Option<DefId>,
134 }
135
136 #[derive(Clone, Hash, RustcEncodable, RustcDecodable)]
137 pub struct ForeignModule {
138     pub foreign_items: Vec<DefId>,
139     pub def_id: DefId,
140 }
141
142 pub enum LoadedMacro {
143     MacroDef(ast::Item),
144     ProcMacro(Lrc<SyntaxExtension>),
145 }
146
147 #[derive(Copy, Clone, Debug)]
148 pub struct ExternCrate {
149     pub src: ExternCrateSource,
150
151     /// span of the extern crate that caused this to be loaded
152     pub span: Span,
153
154     /// Number of links to reach the extern;
155     /// used to select the extern with the shortest path
156     pub path_len: usize,
157
158     /// If true, then this crate is the crate named by the extern
159     /// crate referenced above. If false, then this crate is a dep
160     /// of the crate.
161     pub direct: bool,
162 }
163
164 #[derive(Copy, Clone, Debug)]
165 pub enum ExternCrateSource {
166     /// Crate is loaded by `extern crate`.
167     Extern(
168         /// def_id of the item in the current crate that caused
169         /// this crate to be loaded; note that there could be multiple
170         /// such ids
171         DefId,
172     ),
173     // Crate is loaded by `use`.
174     Use,
175     /// Crate is implicitly loaded by an absolute or an `extern::` path.
176     Path,
177 }
178
179 pub struct EncodedMetadata {
180     pub raw_data: Vec<u8>
181 }
182
183 impl EncodedMetadata {
184     pub fn new() -> EncodedMetadata {
185         EncodedMetadata {
186             raw_data: Vec::new(),
187         }
188     }
189 }
190
191 /// The backend's way to give the crate store access to the metadata in a library.
192 /// Note that it returns the raw metadata bytes stored in the library file, whether
193 /// it is compressed, uncompressed, some weird mix, etc.
194 /// rmeta files are backend independent and not handled here.
195 ///
196 /// At the time of this writing, there is only one backend and one way to store
197 /// metadata in library -- this trait just serves to decouple rustc_metadata from
198 /// the archive reader, which depends on LLVM.
199 pub trait MetadataLoader {
200     fn get_rlib_metadata(&self,
201                          target: &Target,
202                          filename: &Path)
203                          -> Result<MetadataRef, String>;
204     fn get_dylib_metadata(&self,
205                           target: &Target,
206                           filename: &Path)
207                           -> Result<MetadataRef, String>;
208 }
209
210 /// A store of Rust crates, through with their metadata
211 /// can be accessed.
212 ///
213 /// Note that this trait should probably not be expanding today. All new
214 /// functionality should be driven through queries instead!
215 ///
216 /// If you find a method on this trait named `{name}_untracked` it signifies
217 /// that it's *not* tracked for dependency information throughout compilation
218 /// (it'd break incremental compilation) and should only be called pre-HIR (e.g.
219 /// during resolve)
220 pub trait CrateStore {
221     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>;
222
223     // access to the metadata loader
224     fn metadata_loader(&self) -> &dyn MetadataLoader;
225
226     // resolve
227     fn def_key(&self, def: DefId) -> DefKey;
228     fn def_path(&self, def: DefId) -> hir_map::DefPath;
229     fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash;
230     fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable>;
231
232     // "queries" used in resolve that aren't tracked for incremental compilation
233     fn visibility_untracked(&self, def: DefId) -> ty::Visibility;
234     fn export_macros_untracked(&self, cnum: CrateNum);
235     fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind;
236     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol;
237     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator;
238     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh;
239     fn crate_edition_untracked(&self, cnum: CrateNum) -> Edition;
240     fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name>;
241     fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export>;
242     fn load_macro_untracked(&self, did: DefId, sess: &Session) -> LoadedMacro;
243     fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum>;
244     fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics;
245     fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem;
246     fn postorder_cnums_untracked(&self) -> Vec<CrateNum>;
247
248     // This is basically a 1-based range of ints, which is a little
249     // silly - I may fix that.
250     fn crates_untracked(&self) -> Vec<CrateNum>;
251
252     // utility functions
253     fn encode_metadata<'a, 'tcx>(&self,
254                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
255                                  link_meta: &LinkMeta)
256                                  -> EncodedMetadata;
257     fn metadata_encoding_version(&self) -> &[u8];
258 }
259
260 pub type CrateStoreDyn = dyn CrateStore + sync::Sync;
261
262 // FIXME: find a better place for this?
263 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
264     let mut err_count = 0;
265     {
266         let mut say = |s: &str| {
267             match (sp, sess) {
268                 (_, None) => bug!("{}", s),
269                 (Some(sp), Some(sess)) => sess.span_err(sp, s),
270                 (None, Some(sess)) => sess.err(s),
271             }
272             err_count += 1;
273         };
274         if s.is_empty() {
275             say("crate name must not be empty");
276         }
277         for c in s.chars() {
278             if c.is_alphanumeric() { continue }
279             if c == '_'  { continue }
280             say(&format!("invalid character `{}` in crate name: `{}`", c, s));
281         }
282     }
283
284     if err_count > 0 {
285         sess.unwrap().abort_if_errors();
286     }
287 }
288
289 /// A dummy crate store that does not support any non-local crates,
290 /// for test purposes.
291 pub struct DummyCrateStore;
292
293 #[allow(unused_variables)]
294 impl CrateStore for DummyCrateStore {
295     fn crate_data_as_rc_any(&self, krate: CrateNum) -> Lrc<dyn Any>
296         { bug!("crate_data_as_rc_any") }
297     // item info
298     fn visibility_untracked(&self, def: DefId) -> ty::Visibility { bug!("visibility") }
299     fn item_generics_cloned_untracked(&self, def: DefId, sess: &Session) -> ty::Generics
300         { bug!("item_generics_cloned") }
301
302     // trait/impl-item info
303     fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem
304         { bug!("associated_item_cloned") }
305
306     // crate metadata
307     fn dep_kind_untracked(&self, cnum: CrateNum) -> DepKind { bug!("is_explicitly_linked") }
308     fn export_macros_untracked(&self, cnum: CrateNum) { bug!("export_macros") }
309     fn crate_name_untracked(&self, cnum: CrateNum) -> Symbol { bug!("crate_name") }
310     fn crate_disambiguator_untracked(&self, cnum: CrateNum) -> CrateDisambiguator {
311         bug!("crate_disambiguator")
312     }
313     fn crate_hash_untracked(&self, cnum: CrateNum) -> Svh { bug!("crate_hash") }
314     fn crate_edition_untracked(&self, cnum: CrateNum) -> Edition { bug!("crate_edition_untracked") }
315
316     // resolve
317     fn def_key(&self, def: DefId) -> DefKey { bug!("def_key") }
318     fn def_path(&self, def: DefId) -> hir_map::DefPath {
319         bug!("relative_def_path")
320     }
321     fn def_path_hash(&self, def: DefId) -> hir_map::DefPathHash {
322         bug!("def_path_hash")
323     }
324     fn def_path_table(&self, cnum: CrateNum) -> Lrc<DefPathTable> {
325         bug!("def_path_table")
326     }
327     fn struct_field_names_untracked(&self, def: DefId) -> Vec<ast::Name> {
328         bug!("struct_field_names")
329     }
330     fn item_children_untracked(&self, did: DefId, sess: &Session) -> Vec<def::Export> {
331         bug!("item_children")
332     }
333     fn load_macro_untracked(&self, did: DefId, sess: &Session) -> LoadedMacro { bug!("load_macro") }
334
335     fn crates_untracked(&self) -> Vec<CrateNum> { vec![] }
336
337     // utility functions
338     fn extern_mod_stmt_cnum_untracked(&self, emod_id: ast::NodeId) -> Option<CrateNum> { None }
339     fn encode_metadata<'a, 'tcx>(&self,
340                                  tcx: TyCtxt<'a, 'tcx, 'tcx>,
341                                  link_meta: &LinkMeta)
342                                  -> EncodedMetadata {
343         bug!("encode_metadata")
344     }
345     fn metadata_encoding_version(&self) -> &[u8] { bug!("metadata_encoding_version") }
346     fn postorder_cnums_untracked(&self) -> Vec<CrateNum> { bug!("postorder_cnums_untracked") }
347
348     // access to the metadata loader
349     fn metadata_loader(&self) -> &dyn MetadataLoader { bug!("metadata_loader") }
350 }
351
352 pub trait CrateLoader {
353     fn process_extern_crate(&mut self, item: &ast::Item, defs: &Definitions) -> CrateNum;
354
355     fn process_path_extern(
356         &mut self,
357         name: Symbol,
358         span: Span,
359     ) -> CrateNum;
360
361     fn process_use_extern(
362         &mut self,
363         name: Symbol,
364         span: Span,
365         id: ast::NodeId,
366         defs: &Definitions,
367     ) -> CrateNum;
368
369     fn postprocess(&mut self, krate: &ast::Crate);
370 }
371
372 // This method is used when generating the command line to pass through to
373 // system linker. The linker expects undefined symbols on the left of the
374 // command line to be defined in libraries on the right, not the other way
375 // around. For more info, see some comments in the add_used_library function
376 // below.
377 //
378 // In order to get this left-to-right dependency ordering, we perform a
379 // topological sort of all crates putting the leaves at the right-most
380 // positions.
381 pub fn used_crates(tcx: TyCtxt, prefer: LinkagePreference)
382     -> Vec<(CrateNum, LibSource)>
383 {
384     let mut libs = tcx.crates()
385         .iter()
386         .cloned()
387         .filter_map(|cnum| {
388             if tcx.dep_kind(cnum).macros_only() {
389                 return None
390             }
391             let source = tcx.used_crate_source(cnum);
392             let path = match prefer {
393                 LinkagePreference::RequireDynamic => source.dylib.clone().map(|p| p.0),
394                 LinkagePreference::RequireStatic => source.rlib.clone().map(|p| p.0),
395             };
396             let path = match path {
397                 Some(p) => LibSource::Some(p),
398                 None => {
399                     if source.rmeta.is_some() {
400                         LibSource::MetadataOnly
401                     } else {
402                         LibSource::None
403                     }
404                 }
405             };
406             Some((cnum, path))
407         })
408         .collect::<Vec<_>>();
409     let mut ordering = tcx.postorder_cnums(LOCAL_CRATE);
410     Lrc::make_mut(&mut ordering).reverse();
411     libs.sort_by_cached_key(|&(a, _)| {
412         ordering.iter().position(|x| *x == a)
413     });
414     libs
415 }