]> git.lizzy.rs Git - rust.git/blob - src/librustc/metadata/creader.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[rust.git] / src / librustc / metadata / creader.rs
1 // Copyright 2012-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 #![allow(non_camel_case_types)]
12
13 //! Validates all used crates and extern libraries and loads their metadata
14
15 use back::svh::Svh;
16 use session::{config, Session};
17 use session::search_paths::PathKind;
18 use metadata::cstore;
19 use metadata::cstore::{CStore, CrateSource, MetadataBlob};
20 use metadata::decoder;
21 use metadata::loader;
22 use metadata::loader::CratePaths;
23
24 use std::rc::Rc;
25 use syntax::ast;
26 use syntax::abi;
27 use syntax::attr;
28 use syntax::attr::AttrMetaMethods;
29 use syntax::codemap::{Span, mk_sp};
30 use syntax::parse;
31 use syntax::parse::token::InternedString;
32 use syntax::parse::token;
33 use syntax::visit;
34 use util::fs;
35 use log;
36
37 pub struct CrateReader<'a> {
38     sess: &'a Session,
39     next_crate_num: ast::CrateNum,
40 }
41
42 impl<'a, 'v> visit::Visitor<'v> for CrateReader<'a> {
43     fn visit_item(&mut self, a: &ast::Item) {
44         self.process_item(a);
45         visit::walk_item(self, a);
46     }
47 }
48
49 fn dump_crates(cstore: &CStore) {
50     debug!("resolved crates:");
51     cstore.iter_crate_data_origins(|_, data, opt_source| {
52         debug!("  name: {}", data.name());
53         debug!("  cnum: {}", data.cnum);
54         debug!("  hash: {}", data.hash());
55         opt_source.map(|cs| {
56             let CrateSource { dylib, rlib, cnum: _ } = cs;
57             dylib.map(|dl| debug!("  dylib: {}", dl.0.display()));
58             rlib.map(|rl|  debug!("   rlib: {}", rl.0.display()));
59         });
60     })
61 }
62
63 fn should_link(i: &ast::Item) -> bool {
64     !attr::contains_name(&i.attrs[], "no_link")
65 }
66
67 struct CrateInfo {
68     ident: String,
69     name: String,
70     id: ast::NodeId,
71     should_link: bool,
72 }
73
74 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
75     let err = |s: &str| {
76         match (sp, sess) {
77             (_, None) => panic!("{}", s),
78             (Some(sp), Some(sess)) => sess.span_err(sp, s),
79             (None, Some(sess)) => sess.err(s),
80         }
81     };
82     if s.len() == 0 {
83         err("crate name must not be empty");
84     }
85     for c in s.chars() {
86         if c.is_alphanumeric() { continue }
87         if c == '_' || c == '-' { continue }
88         err(&format!("invalid character `{}` in crate name: `{}`", c, s)[]);
89     }
90     match sess {
91         Some(sess) => sess.abort_if_errors(),
92         None => {}
93     }
94 }
95
96
97 fn register_native_lib(sess: &Session,
98                        span: Option<Span>,
99                        name: String,
100                        kind: cstore::NativeLibraryKind) {
101     if name.is_empty() {
102         match span {
103             Some(span) => {
104                 sess.span_err(span, "#[link(name = \"\")] given with \
105                                      empty name");
106             }
107             None => {
108                 sess.err("empty library name given via `-l`");
109             }
110         }
111         return
112     }
113     let is_osx = sess.target.target.options.is_like_osx;
114     if kind == cstore::NativeFramework && !is_osx {
115         let msg = "native frameworks are only available on OSX targets";
116         match span {
117             Some(span) => sess.span_err(span, msg),
118             None => sess.err(msg),
119         }
120     }
121     sess.cstore.add_used_library(name, kind);
122 }
123
124 // Extra info about a crate loaded for plugins or exported macros.
125 struct ExtensionCrate {
126     metadata: PMDSource,
127     dylib: Option<Path>,
128     target_only: bool,
129 }
130
131 enum PMDSource {
132     Registered(Rc<cstore::crate_metadata>),
133     Owned(MetadataBlob),
134 }
135
136 impl PMDSource {
137     pub fn as_slice<'a>(&'a self) -> &'a [u8] {
138         match *self {
139             PMDSource::Registered(ref cmd) => cmd.data(),
140             PMDSource::Owned(ref mdb) => mdb.as_slice(),
141         }
142     }
143 }
144
145 impl<'a> CrateReader<'a> {
146     pub fn new(sess: &'a Session) -> CrateReader<'a> {
147         CrateReader {
148             sess: sess,
149             next_crate_num: sess.cstore.next_crate_num(),
150         }
151     }
152
153     // Traverses an AST, reading all the information about use'd crates and extern
154     // libraries necessary for later resolving, typechecking, linking, etc.
155     pub fn read_crates(&mut self, krate: &ast::Crate) {
156         self.process_crate(krate);
157         visit::walk_crate(self, krate);
158
159         if log_enabled!(log::DEBUG) {
160             dump_crates(&self.sess.cstore);
161         }
162
163         for &(ref name, kind) in &self.sess.opts.libs {
164             register_native_lib(self.sess, None, name.clone(), kind);
165         }
166     }
167
168     fn process_crate(&self, c: &ast::Crate) {
169         for a in c.attrs.iter().filter(|m| m.name() == "link_args") {
170             match a.value_str() {
171                 Some(ref linkarg) => self.sess.cstore.add_used_link_args(&linkarg),
172                 None => { /* fallthrough */ }
173             }
174         }
175     }
176
177     fn extract_crate_info(&self, i: &ast::Item) -> Option<CrateInfo> {
178         match i.node {
179             ast::ItemExternCrate(ref path_opt) => {
180                 let ident = token::get_ident(i.ident);
181                 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
182                        ident, path_opt);
183                 let name = match *path_opt {
184                     Some((ref path_str, _)) => {
185                         let name = path_str.to_string();
186                         validate_crate_name(Some(self.sess), &name[..],
187                                             Some(i.span));
188                         name
189                     }
190                     None => ident.to_string(),
191                 };
192                 Some(CrateInfo {
193                     ident: ident.to_string(),
194                     name: name,
195                     id: i.id,
196                     should_link: should_link(i),
197                 })
198             }
199             _ => None
200         }
201     }
202
203     fn process_item(&mut self, i: &ast::Item) {
204         match i.node {
205             ast::ItemExternCrate(_) => {
206                 if !should_link(i) {
207                     return;
208                 }
209
210                 match self.extract_crate_info(i) {
211                     Some(info) => {
212                         let (cnum, _, _) = self.resolve_crate(&None,
213                                                               &info.ident[],
214                                                               &info.name[],
215                                                               None,
216                                                               i.span,
217                                                               PathKind::Crate);
218                         self.sess.cstore.add_extern_mod_stmt_cnum(info.id, cnum);
219                     }
220                     None => ()
221                 }
222             }
223             ast::ItemForeignMod(ref fm) => {
224                 if fm.abi == abi::Rust || fm.abi == abi::RustIntrinsic {
225                     return;
226                 }
227
228                 // First, add all of the custom link_args attributes
229                 let link_args = i.attrs.iter()
230                     .filter_map(|at| if at.name() == "link_args" {
231                         Some(at)
232                     } else {
233                         None
234                     })
235                     .collect::<Vec<&ast::Attribute>>();
236                 for m in &link_args {
237                     match m.value_str() {
238                         Some(linkarg) => self.sess.cstore.add_used_link_args(&linkarg),
239                         None => { /* fallthrough */ }
240                     }
241                 }
242
243                 // Next, process all of the #[link(..)]-style arguments
244                 let link_args = i.attrs.iter()
245                     .filter_map(|at| if at.name() == "link" {
246                         Some(at)
247                     } else {
248                         None
249                     })
250                     .collect::<Vec<&ast::Attribute>>();
251                 for m in &link_args {
252                     match m.meta_item_list() {
253                         Some(items) => {
254                             let kind = items.iter().find(|k| {
255                                 k.name() == "kind"
256                             }).and_then(|a| a.value_str());
257                             let kind = match kind {
258                                 Some(k) => {
259                                     if k == "static" {
260                                         cstore::NativeStatic
261                                     } else if self.sess.target.target.options.is_like_osx
262                                               && k == "framework" {
263                                         cstore::NativeFramework
264                                     } else if k == "framework" {
265                                         cstore::NativeFramework
266                                     } else if k == "dylib" {
267                                         cstore::NativeUnknown
268                                     } else {
269                                         self.sess.span_err(m.span,
270                                             &format!("unknown kind: `{}`",
271                                                     k)[]);
272                                         cstore::NativeUnknown
273                                     }
274                                 }
275                                 None => cstore::NativeUnknown
276                             };
277                             let n = items.iter().find(|n| {
278                                 n.name() == "name"
279                             }).and_then(|a| a.value_str());
280                             let n = match n {
281                                 Some(n) => n,
282                                 None => {
283                                     self.sess.span_err(m.span,
284                                         "#[link(...)] specified without \
285                                          `name = \"foo\"`");
286                                     InternedString::new("foo")
287                                 }
288                             };
289                             register_native_lib(self.sess, Some(m.span),
290                                                 n.to_string(), kind);
291                         }
292                         None => {}
293                     }
294                 }
295             }
296             _ => { }
297         }
298     }
299
300     fn existing_match(&self, name: &str, hash: Option<&Svh>, kind: PathKind)
301                       -> Option<ast::CrateNum> {
302         let mut ret = None;
303         self.sess.cstore.iter_crate_data(|cnum, data| {
304             if data.name != name { return }
305
306             match hash {
307                 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
308                 Some(..) => return,
309                 None => {}
310             }
311
312             // When the hash is None we're dealing with a top-level dependency
313             // in which case we may have a specification on the command line for
314             // this library. Even though an upstream library may have loaded
315             // something of the same name, we have to make sure it was loaded
316             // from the exact same location as well.
317             //
318             // We're also sure to compare *paths*, not actual byte slices. The
319             // `source` stores paths which are normalized which may be different
320             // from the strings on the command line.
321             let source = self.sess.cstore.get_used_crate_source(cnum).unwrap();
322             if let Some(locs) = self.sess.opts.externs.get(name) {
323                 let found = locs.iter().any(|l| {
324                     let l = fs::realpath(&Path::new(&l[..])).ok();
325                     source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
326                     source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
327                 });
328                 if found {
329                     ret = Some(cnum);
330                 }
331                 return
332             }
333
334             // Alright, so we've gotten this far which means that `data` has the
335             // right name, we don't have a hash, and we don't have a --extern
336             // pointing for ourselves. We're still not quite yet done because we
337             // have to make sure that this crate was found in the crate lookup
338             // path (this is a top-level dependency) as we don't want to
339             // implicitly load anything inside the dependency lookup path.
340             let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
341                                   .unwrap().1;
342             if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
343                 ret = Some(cnum);
344             }
345         });
346         return ret;
347     }
348
349     fn register_crate(&mut self,
350                       root: &Option<CratePaths>,
351                       ident: &str,
352                       name: &str,
353                       span: Span,
354                       lib: loader::Library)
355                       -> (ast::CrateNum, Rc<cstore::crate_metadata>,
356                           cstore::CrateSource) {
357         // Claim this crate number and cache it
358         let cnum = self.next_crate_num;
359         self.next_crate_num += 1;
360
361         // Stash paths for top-most crate locally if necessary.
362         let crate_paths = if root.is_none() {
363             Some(CratePaths {
364                 ident: ident.to_string(),
365                 dylib: lib.dylib.clone().map(|p| p.0),
366                 rlib:  lib.rlib.clone().map(|p| p.0),
367             })
368         } else {
369             None
370         };
371         // Maintain a reference to the top most crate.
372         let root = if root.is_some() { root } else { &crate_paths };
373
374         let cnum_map = self.resolve_crate_deps(root, lib.metadata.as_slice(), span);
375
376         let loader::Library{ dylib, rlib, metadata } = lib;
377
378         let cmeta = Rc::new( cstore::crate_metadata {
379             name: name.to_string(),
380             data: metadata,
381             cnum_map: cnum_map,
382             cnum: cnum,
383             span: span,
384         });
385
386         let source = cstore::CrateSource {
387             dylib: dylib,
388             rlib: rlib,
389             cnum: cnum,
390         };
391
392         self.sess.cstore.set_crate_data(cnum, cmeta.clone());
393         self.sess.cstore.add_used_crate_source(source.clone());
394         (cnum, cmeta, source)
395     }
396
397     fn resolve_crate(&mut self,
398                      root: &Option<CratePaths>,
399                      ident: &str,
400                      name: &str,
401                      hash: Option<&Svh>,
402                      span: Span,
403                      kind: PathKind)
404                          -> (ast::CrateNum, Rc<cstore::crate_metadata>,
405                              cstore::CrateSource) {
406         match self.existing_match(name, hash, kind) {
407             None => {
408                 let mut load_ctxt = loader::Context {
409                     sess: self.sess,
410                     span: span,
411                     ident: ident,
412                     crate_name: name,
413                     hash: hash.map(|a| &*a),
414                     filesearch: self.sess.target_filesearch(kind),
415                     target: &self.sess.target.target,
416                     triple: &self.sess.opts.target_triple[],
417                     root: root,
418                     rejected_via_hash: vec!(),
419                     rejected_via_triple: vec!(),
420                     rejected_via_kind: vec!(),
421                     should_match_name: true,
422                 };
423                 let library = load_ctxt.load_library_crate();
424                 self.register_crate(root, ident, name, span, library)
425             }
426             Some(cnum) => (cnum,
427                            self.sess.cstore.get_crate_data(cnum),
428                            self.sess.cstore.get_used_crate_source(cnum).unwrap())
429         }
430     }
431
432     // Go through the crate metadata and load any crates that it references
433     fn resolve_crate_deps(&mut self,
434                           root: &Option<CratePaths>,
435                           cdata: &[u8], span : Span)
436                        -> cstore::cnum_map {
437         debug!("resolving deps of external crate");
438         // The map from crate numbers in the crate we're resolving to local crate
439         // numbers
440         decoder::get_crate_deps(cdata).iter().map(|dep| {
441             debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
442             let (local_cnum, _, _) = self.resolve_crate(root,
443                                                    &dep.name[],
444                                                    &dep.name[],
445                                                    Some(&dep.hash),
446                                                    span,
447                                                    PathKind::Dependency);
448             (dep.cnum, local_cnum)
449         }).collect()
450     }
451
452     fn read_extension_crate(&mut self, span: Span, info: &CrateInfo) -> ExtensionCrate {
453         let target_triple = &self.sess.opts.target_triple[];
454         let is_cross = target_triple != config::host_triple();
455         let mut should_link = info.should_link && !is_cross;
456         let mut target_only = false;
457         let ident = info.ident.clone();
458         let name = info.name.clone();
459         let mut load_ctxt = loader::Context {
460             sess: self.sess,
461             span: span,
462             ident: &ident[..],
463             crate_name: &name[..],
464             hash: None,
465             filesearch: self.sess.host_filesearch(PathKind::Crate),
466             target: &self.sess.host,
467             triple: config::host_triple(),
468             root: &None,
469             rejected_via_hash: vec!(),
470             rejected_via_triple: vec!(),
471             rejected_via_kind: vec!(),
472             should_match_name: true,
473         };
474         let library = match load_ctxt.maybe_load_library_crate() {
475             Some(l) => l,
476             None if is_cross => {
477                 // Try loading from target crates. This will abort later if we
478                 // try to load a plugin registrar function,
479                 target_only = true;
480                 should_link = info.should_link;
481
482                 load_ctxt.target = &self.sess.target.target;
483                 load_ctxt.triple = target_triple;
484                 load_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
485                 load_ctxt.load_library_crate()
486             }
487             None => { load_ctxt.report_load_errs(); unreachable!() },
488         };
489
490         let dylib = library.dylib.clone();
491         let register = should_link && self.existing_match(info.name.as_slice(),
492                                                           None,
493                                                           PathKind::Crate).is_none();
494         let metadata = if register {
495             // Register crate now to avoid double-reading metadata
496             let (_, cmd, _) = self.register_crate(&None, &info.ident[],
497                                 &info.name[], span, library);
498             PMDSource::Registered(cmd)
499         } else {
500             // Not registering the crate; just hold on to the metadata
501             PMDSource::Owned(library.metadata)
502         };
503
504         ExtensionCrate {
505             metadata: metadata,
506             dylib: dylib.map(|p| p.0),
507             target_only: target_only,
508         }
509     }
510
511     /// Read exported macros.
512     pub fn read_exported_macros(&mut self, krate: &ast::Item) -> Vec<ast::MacroDef> {
513         let ci = self.extract_crate_info(krate).unwrap();
514         let ekrate = self.read_extension_crate(krate.span, &ci);
515
516         let source_name = format!("<{} macros>", krate.ident);
517         let mut macros = vec![];
518         decoder::each_exported_macro(ekrate.metadata.as_slice(),
519                                      &*self.sess.cstore.intr,
520             |name, attrs, body| {
521                 // NB: Don't use parse::parse_tts_from_source_str because it parses with
522                 // quote_depth > 0.
523                 let mut p = parse::new_parser_from_source_str(&self.sess.parse_sess,
524                                                               self.sess.opts.cfg.clone(),
525                                                               source_name.clone(),
526                                                               body);
527                 let lo = p.span.lo;
528                 let body = p.parse_all_token_trees();
529                 let span = mk_sp(lo, p.last_span.hi);
530                 p.abort_if_errors();
531                 macros.push(ast::MacroDef {
532                     ident: name.ident(),
533                     attrs: attrs,
534                     id: ast::DUMMY_NODE_ID,
535                     span: span,
536                     imported_from: Some(krate.ident),
537                     // overridden in plugin/load.rs
538                     export: false,
539                     use_locally: false,
540
541                     body: body,
542                 });
543                 true
544             }
545         );
546         macros
547     }
548
549     /// Look for a plugin registrar. Returns library path and symbol name.
550     pub fn find_plugin_registrar(&mut self, span: Span, name: &str) -> Option<(Path, String)> {
551         let ekrate = self.read_extension_crate(span, &CrateInfo {
552              name: name.to_string(),
553              ident: name.to_string(),
554              id: ast::DUMMY_NODE_ID,
555              should_link: false,
556         });
557
558         if ekrate.target_only {
559             // Need to abort before syntax expansion.
560             let message = format!("plugin `{}` is not available for triple `{}` \
561                                    (only found {})",
562                                   name,
563                                   config::host_triple(),
564                                   self.sess.opts.target_triple);
565             self.sess.span_err(span, &message[..]);
566             self.sess.abort_if_errors();
567         }
568
569         let registrar = decoder::get_plugin_registrar_fn(ekrate.metadata.as_slice())
570             .map(|id| decoder::get_symbol(ekrate.metadata.as_slice(), id));
571
572         match (ekrate.dylib.as_ref(), registrar) {
573             (Some(dylib), Some(reg)) => Some((dylib.clone(), reg)),
574             (None, Some(_)) => {
575                 let message = format!("plugin `{}` only found in rlib format, \
576                                        but must be available in dylib format",
577                                        name);
578                 self.sess.span_err(span, &message[..]);
579                 // No need to abort because the loading code will just ignore this
580                 // empty dylib.
581                 None
582             }
583             _ => None,
584         }
585     }
586 }