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