]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/cstore.rs
Auto merge of #29651 - tshepang:misc, 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 back::svh::Svh;
26 use front::map as hir_map;
27 use middle::def;
28 use middle::lang_items;
29 use middle::ty::{self, Ty};
30 use middle::def_id::{DefId, DefIndex};
31 use session::Session;
32 use session::search_paths::PathKind;
33 use util::nodemap::{FnvHashMap, NodeMap, NodeSet};
34 use std::any::Any;
35 use std::cell::RefCell;
36 use std::rc::Rc;
37 use std::path::PathBuf;
38 use syntax::ast;
39 use syntax::ast_util::{IdVisitingOperation};
40 use syntax::attr;
41 use syntax::codemap::Span;
42 use syntax::ptr::P;
43 use rustc_back::target::Target;
44 use rustc_front::hir;
45 use rustc_front::intravisit::Visitor;
46 use rustc_front::util::IdVisitor;
47
48 pub use self::DefLike::{DlDef, DlField, DlImpl};
49 pub use self::NativeLibraryKind::{NativeStatic, NativeFramework, NativeUnknown};
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: String,
56     pub crate_hash: Svh,
57 }
58
59 // Where a crate came from on the local filesystem. One of these two 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 cnum: ast::CrateNum,
66 }
67
68 #[derive(Copy, Debug, PartialEq, Clone)]
69 pub enum LinkagePreference {
70     RequireDynamic,
71     RequireStatic,
72 }
73
74 enum_from_u32! {
75     #[derive(Copy, Clone, PartialEq)]
76     pub enum NativeLibraryKind {
77         NativeStatic,    // native static library (.a archive)
78         NativeFramework, // OSX-specific
79         NativeUnknown,   // default way to specify a dynamic library
80     }
81 }
82
83 // Something that a name can resolve to.
84 #[derive(Copy, Clone, Debug)]
85 pub enum DefLike {
86     DlDef(def::Def),
87     DlImpl(DefId),
88     DlField
89 }
90
91 /// The data we save and restore about an inlined item or method.  This is not
92 /// part of the AST that we parse from a file, but it becomes part of the tree
93 /// that we trans.
94 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)]
95 pub enum InlinedItem {
96     Item(P<hir::Item>),
97     TraitItem(DefId /* impl id */, P<hir::TraitItem>),
98     ImplItem(DefId /* impl id */, P<hir::ImplItem>),
99     Foreign(P<hir::ForeignItem>),
100 }
101
102 /// A borrowed version of `hir::InlinedItem`.
103 pub enum InlinedItemRef<'a> {
104     Item(&'a hir::Item),
105     TraitItem(DefId, &'a hir::TraitItem),
106     ImplItem(DefId, &'a hir::ImplItem),
107     Foreign(&'a hir::ForeignItem)
108 }
109
110 /// Item definitions in the currently-compiled crate would have the CrateNum
111 /// LOCAL_CRATE in their DefId.
112 pub const LOCAL_CRATE: ast::CrateNum = 0;
113
114 pub struct ChildItem {
115     pub def: DefLike,
116     pub name: ast::Name,
117     pub vis: hir::Visibility
118 }
119
120 pub enum FoundAst<'ast> {
121     Found(&'ast InlinedItem),
122     FoundParent(DefId, &'ast InlinedItem),
123     NotFound,
124 }
125
126 /// A store of Rust crates, through with their metadata
127 /// can be accessed.
128 ///
129 /// The `: Any` bound is a temporary measure that allows access
130 /// to the backing `rustc_metadata::cstore::CStore` object. It
131 /// will be removed in the near future - if you need to access
132 /// internal APIs, please tell us.
133 pub trait CrateStore<'tcx> : Any {
134     // item info
135     fn stability(&self, def: DefId) -> Option<attr::Stability>;
136     fn closure_kind(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
137                     -> ty::ClosureKind;
138     fn closure_ty(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
139                   -> ty::ClosureTy<'tcx>;
140     fn item_variances(&self, def: DefId) -> ty::ItemVariances;
141     fn repr_attrs(&self, def: DefId) -> Vec<attr::ReprAttr>;
142     fn item_type(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
143                  -> ty::TypeScheme<'tcx>;
144     fn item_path(&self, def: DefId) -> Vec<hir_map::PathElem>;
145     fn item_name(&self, def: DefId) -> ast::Name;
146     fn item_predicates(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
147                        -> ty::GenericPredicates<'tcx>;
148     fn item_super_predicates(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
149                              -> ty::GenericPredicates<'tcx>;
150     fn item_attrs(&self, def_id: DefId) -> Vec<ast::Attribute>;
151     fn item_symbol(&self, def: DefId) -> String;
152     fn trait_def(&self, tcx: &ty::ctxt<'tcx>, def: DefId)-> ty::TraitDef<'tcx>;
153     fn adt_def(&self, tcx: &ty::ctxt<'tcx>, def: DefId) -> ty::AdtDefMaster<'tcx>;
154     fn method_arg_names(&self, did: DefId) -> Vec<String>;
155     fn inherent_implementations_for_type(&self, def_id: DefId) -> Vec<DefId>;
156
157     // trait info
158     fn implementations_of_trait(&self, def_id: DefId) -> Vec<DefId>;
159     fn provided_trait_methods(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
160                               -> Vec<Rc<ty::Method<'tcx>>>;
161     fn trait_item_def_ids(&self, def: DefId)
162                           -> Vec<ty::ImplOrTraitItemId>;
163
164     // impl info
165     fn impl_items(&self, impl_def_id: DefId) -> Vec<ty::ImplOrTraitItemId>;
166     fn impl_trait_ref(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
167                       -> Option<ty::TraitRef<'tcx>>;
168     fn impl_polarity(&self, def: DefId) -> Option<hir::ImplPolarity>;
169     fn custom_coerce_unsized_kind(&self, def: DefId)
170                                   -> Option<ty::adjustment::CustomCoerceUnsized>;
171     fn associated_consts(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
172                          -> Vec<Rc<ty::AssociatedConst<'tcx>>>;
173
174     // trait/impl-item info
175     fn trait_of_item(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
176                      -> Option<DefId>;
177     fn impl_or_trait_item(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
178                           -> ty::ImplOrTraitItem<'tcx>;
179
180     // flags
181     fn is_const_fn(&self, did: DefId) -> bool;
182     fn is_defaulted_trait(&self, did: DefId) -> bool;
183     fn is_impl(&self, did: DefId) -> bool;
184     fn is_default_impl(&self, impl_did: DefId) -> bool;
185     fn is_extern_fn(&self, tcx: &ty::ctxt<'tcx>, did: DefId) -> bool;
186     fn is_static(&self, did: DefId) -> bool;
187     fn is_static_method(&self, did: DefId) -> bool;
188     fn is_statically_included_foreign_item(&self, id: ast::NodeId) -> bool;
189     fn is_typedef(&self, did: DefId) -> bool;
190
191     // crate metadata
192     fn dylib_dependency_formats(&self, cnum: ast::CrateNum)
193                                     -> Vec<(ast::CrateNum, LinkagePreference)>;
194     fn lang_items(&self, cnum: ast::CrateNum) -> Vec<(DefIndex, usize)>;
195     fn missing_lang_items(&self, cnum: ast::CrateNum) -> Vec<lang_items::LangItem>;
196     fn is_staged_api(&self, cnum: ast::CrateNum) -> bool;
197     fn is_explicitly_linked(&self, cnum: ast::CrateNum) -> bool;
198     fn is_allocator(&self, cnum: ast::CrateNum) -> bool;
199     fn crate_attrs(&self, cnum: ast::CrateNum) -> Vec<ast::Attribute>;
200     fn crate_name(&self, cnum: ast::CrateNum) -> String;
201     fn crate_hash(&self, cnum: ast::CrateNum) -> Svh;
202     fn crate_struct_field_attrs(&self, cnum: ast::CrateNum)
203                                 -> FnvHashMap<DefId, Vec<ast::Attribute>>;
204     fn plugin_registrar_fn(&self, cnum: ast::CrateNum) -> Option<DefId>;
205     fn native_libraries(&self, cnum: ast::CrateNum) -> Vec<(NativeLibraryKind, String)>;
206     fn reachable_ids(&self, cnum: ast::CrateNum) -> Vec<DefId>;
207
208     // resolve
209     fn def_path(&self, def: DefId) -> hir_map::DefPath;
210     fn tuple_struct_definition_if_ctor(&self, did: DefId) -> Option<DefId>;
211     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name>;
212     fn item_children(&self, did: DefId) -> Vec<ChildItem>;
213     fn crate_top_level_items(&self, cnum: ast::CrateNum) -> Vec<ChildItem>;
214
215     // misc. metadata
216     fn maybe_get_item_ast(&'tcx self, tcx: &ty::ctxt<'tcx>, def: DefId)
217                           -> FoundAst<'tcx>;
218     // This is basically a 1-based range of ints, which is a little
219     // silly - I may fix that.
220     fn crates(&self) -> Vec<ast::CrateNum>;
221     fn used_libraries(&self) -> Vec<(String, NativeLibraryKind)>;
222     fn used_link_args(&self) -> Vec<String>;
223
224     // utility functions
225     fn metadata_filename(&self) -> &str;
226     fn metadata_section_name(&self, target: &Target) -> &str;
227     fn encode_type(&self, tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Vec<u8>;
228     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)>;
229     fn used_crate_source(&self, cnum: ast::CrateNum) -> CrateSource;
230     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum>;
231     fn encode_metadata(&self,
232                        tcx: &ty::ctxt<'tcx>,
233                        reexports: &def::ExportMap,
234                        item_symbols: &RefCell<NodeMap<String>>,
235                        link_meta: &LinkMeta,
236                        reachable: &NodeSet,
237                        krate: &hir::Crate) -> Vec<u8>;
238     fn metadata_encoding_version(&self) -> &[u8];
239 }
240
241 impl InlinedItem {
242     pub fn visit<'ast,V>(&'ast self, visitor: &mut V)
243         where V: Visitor<'ast>
244     {
245         match *self {
246             InlinedItem::Item(ref i) => visitor.visit_item(&**i),
247             InlinedItem::Foreign(ref i) => visitor.visit_foreign_item(&**i),
248             InlinedItem::TraitItem(_, ref ti) => visitor.visit_trait_item(ti),
249             InlinedItem::ImplItem(_, ref ii) => visitor.visit_impl_item(ii),
250         }
251     }
252
253     pub fn visit_ids<O: IdVisitingOperation>(&self, operation: &mut O) {
254         let mut id_visitor = IdVisitor::new(operation);
255         self.visit(&mut id_visitor);
256     }
257 }
258
259 // FIXME: find a better place for this?
260 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
261     let say = |s: &str| {
262         match (sp, sess) {
263             (_, None) => panic!("{}", s),
264             (Some(sp), Some(sess)) => sess.span_err(sp, s),
265             (None, Some(sess)) => sess.err(s),
266         }
267     };
268     if s.is_empty() {
269         say("crate name must not be empty");
270     }
271     for c in s.chars() {
272         if c.is_alphanumeric() { continue }
273         if c == '_'  { continue }
274         say(&format!("invalid character `{}` in crate name: `{}`", c, s));
275     }
276     match sess {
277         Some(sess) => sess.abort_if_errors(),
278         None => {}
279     }
280 }
281
282 /// A dummy crate store that does not support any non-local crates,
283 /// for test purposes.
284 pub struct DummyCrateStore;
285 #[allow(unused_variables)]
286 impl<'tcx> CrateStore<'tcx> for DummyCrateStore {
287     // item info
288     fn stability(&self, def: DefId) -> Option<attr::Stability> { unimplemented!() }
289     fn closure_kind(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
290                     -> ty::ClosureKind  { unimplemented!() }
291     fn closure_ty(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
292                   -> ty::ClosureTy<'tcx>  { unimplemented!() }
293     fn item_variances(&self, def: DefId) -> ty::ItemVariances { unimplemented!() }
294     fn repr_attrs(&self, def: DefId) -> Vec<attr::ReprAttr> { unimplemented!() }
295     fn item_type(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
296                  -> ty::TypeScheme<'tcx> { unimplemented!() }
297     fn item_path(&self, def: DefId) -> Vec<hir_map::PathElem> { unimplemented!() }
298     fn item_name(&self, def: DefId) -> ast::Name { unimplemented!() }
299     fn item_predicates(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
300                        -> ty::GenericPredicates<'tcx> { unimplemented!() }
301     fn item_super_predicates(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
302                              -> ty::GenericPredicates<'tcx> { unimplemented!() }
303     fn item_attrs(&self, def_id: DefId) -> Vec<ast::Attribute> { unimplemented!() }
304     fn item_symbol(&self, def: DefId) -> String { unimplemented!() }
305     fn trait_def(&self, tcx: &ty::ctxt<'tcx>, def: DefId)-> ty::TraitDef<'tcx>
306         { unimplemented!() }
307     fn adt_def(&self, tcx: &ty::ctxt<'tcx>, def: DefId) -> ty::AdtDefMaster<'tcx>
308         { unimplemented!() }
309     fn method_arg_names(&self, did: DefId) -> Vec<String> { unimplemented!() }
310     fn inherent_implementations_for_type(&self, def_id: DefId) -> Vec<DefId> { vec![] }
311
312     // trait info
313     fn implementations_of_trait(&self, def_id: DefId) -> Vec<DefId> { vec![] }
314     fn provided_trait_methods(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
315                               -> Vec<Rc<ty::Method<'tcx>>> { unimplemented!() }
316     fn trait_item_def_ids(&self, def: DefId)
317                           -> Vec<ty::ImplOrTraitItemId> { unimplemented!() }
318
319     // impl info
320     fn impl_items(&self, impl_def_id: DefId) -> Vec<ty::ImplOrTraitItemId>
321         { unimplemented!() }
322     fn impl_trait_ref(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
323                       -> Option<ty::TraitRef<'tcx>> { unimplemented!() }
324     fn impl_polarity(&self, def: DefId) -> Option<hir::ImplPolarity> { unimplemented!() }
325     fn custom_coerce_unsized_kind(&self, def: DefId)
326                                   -> Option<ty::adjustment::CustomCoerceUnsized>
327         { unimplemented!() }
328     fn associated_consts(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
329                          -> Vec<Rc<ty::AssociatedConst<'tcx>>> { unimplemented!() }
330
331     // trait/impl-item info
332     fn trait_of_item(&self, tcx: &ty::ctxt<'tcx>, def_id: DefId)
333                      -> Option<DefId> { unimplemented!() }
334     fn impl_or_trait_item(&self, tcx: &ty::ctxt<'tcx>, def: DefId)
335                           -> ty::ImplOrTraitItem<'tcx> { unimplemented!() }
336
337     // flags
338     fn is_const_fn(&self, did: DefId) -> bool { unimplemented!() }
339     fn is_defaulted_trait(&self, did: DefId) -> bool { unimplemented!() }
340     fn is_impl(&self, did: DefId) -> bool { unimplemented!() }
341     fn is_default_impl(&self, impl_did: DefId) -> bool { unimplemented!() }
342     fn is_extern_fn(&self, tcx: &ty::ctxt<'tcx>, did: DefId) -> bool { unimplemented!() }
343     fn is_static(&self, did: DefId) -> bool { unimplemented!() }
344     fn is_static_method(&self, did: DefId) -> bool { unimplemented!() }
345     fn is_statically_included_foreign_item(&self, id: ast::NodeId) -> bool { false }
346     fn is_typedef(&self, did: DefId) -> bool { unimplemented!() }
347
348     // crate metadata
349     fn dylib_dependency_formats(&self, cnum: ast::CrateNum)
350                                     -> Vec<(ast::CrateNum, LinkagePreference)>
351         { unimplemented!() }
352     fn lang_items(&self, cnum: ast::CrateNum) -> Vec<(DefIndex, usize)>
353         { unimplemented!() }
354     fn missing_lang_items(&self, cnum: ast::CrateNum) -> Vec<lang_items::LangItem>
355         { unimplemented!() }
356     fn is_staged_api(&self, cnum: ast::CrateNum) -> bool { unimplemented!() }
357     fn is_explicitly_linked(&self, cnum: ast::CrateNum) -> bool { unimplemented!() }
358     fn is_allocator(&self, cnum: ast::CrateNum) -> bool { unimplemented!() }
359     fn crate_attrs(&self, cnum: ast::CrateNum) -> Vec<ast::Attribute>
360         { unimplemented!() }
361     fn crate_name(&self, cnum: ast::CrateNum) -> String { unimplemented!() }
362     fn crate_hash(&self, cnum: ast::CrateNum) -> Svh { unimplemented!() }
363     fn crate_struct_field_attrs(&self, cnum: ast::CrateNum)
364                                 -> FnvHashMap<DefId, Vec<ast::Attribute>>
365         { unimplemented!() }
366     fn plugin_registrar_fn(&self, cnum: ast::CrateNum) -> Option<DefId>
367         { unimplemented!() }
368     fn native_libraries(&self, cnum: ast::CrateNum) -> Vec<(NativeLibraryKind, String)>
369         { unimplemented!() }
370     fn reachable_ids(&self, cnum: ast::CrateNum) -> Vec<DefId> { unimplemented!() }
371
372     // resolve
373     fn def_path(&self, def: DefId) -> hir_map::DefPath { unimplemented!() }
374     fn tuple_struct_definition_if_ctor(&self, did: DefId) -> Option<DefId>
375         { unimplemented!() }
376     fn struct_field_names(&self, def: DefId) -> Vec<ast::Name> { unimplemented!() }
377     fn item_children(&self, did: DefId) -> Vec<ChildItem> { unimplemented!() }
378     fn crate_top_level_items(&self, cnum: ast::CrateNum) -> Vec<ChildItem>
379         { unimplemented!() }
380
381     // misc. metadata
382     fn maybe_get_item_ast(&'tcx self, tcx: &ty::ctxt<'tcx>, def: DefId)
383                           -> FoundAst<'tcx> { unimplemented!() }
384     // This is basically a 1-based range of ints, which is a little
385     // silly - I may fix that.
386     fn crates(&self) -> Vec<ast::CrateNum> { vec![] }
387     fn used_libraries(&self) -> Vec<(String, NativeLibraryKind)> { vec![] }
388     fn used_link_args(&self) -> Vec<String> { vec![] }
389
390     // utility functions
391     fn metadata_filename(&self) -> &str { unimplemented!() }
392     fn metadata_section_name(&self, target: &Target) -> &str { unimplemented!() }
393     fn encode_type(&self, tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Vec<u8>
394         { unimplemented!() }
395     fn used_crates(&self, prefer: LinkagePreference) -> Vec<(ast::CrateNum, Option<PathBuf>)>
396         { vec![] }
397     fn used_crate_source(&self, cnum: ast::CrateNum) -> CrateSource { unimplemented!() }
398     fn extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<ast::CrateNum> { None }
399     fn encode_metadata(&self,
400                        tcx: &ty::ctxt<'tcx>,
401                        reexports: &def::ExportMap,
402                        item_symbols: &RefCell<NodeMap<String>>,
403                        link_meta: &LinkMeta,
404                        reachable: &NodeSet,
405                        krate: &hir::Crate) -> Vec<u8> { vec![] }
406     fn metadata_encoding_version(&self) -> &[u8] { unimplemented!() }
407 }