]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/creader.rs
renumber diagnostic to avoid conflict
[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 common::rustc_version;
16 use cstore::{self, CStore, CrateSource, MetadataBlob};
17 use decoder;
18 use loader::{self, CratePaths};
19
20 use rustc::back::svh::Svh;
21 use rustc::dep_graph::DepNode;
22 use rustc::session::{config, Session};
23 use rustc::session::search_paths::PathKind;
24 use rustc::middle::cstore::{CrateStore, validate_crate_name, ExternCrate};
25 use rustc::util::nodemap::FnvHashMap;
26 use rustc::front::map as hir_map;
27
28 use std::cell::{RefCell, Cell};
29 use std::path::PathBuf;
30 use std::rc::Rc;
31 use std::fs;
32
33 use syntax::ast;
34 use syntax::abi::Abi;
35 use syntax::codemap::{self, Span, mk_sp, Pos};
36 use syntax::parse;
37 use syntax::attr;
38 use syntax::attr::AttrMetaMethods;
39 use syntax::errors::FatalError;
40 use syntax::parse::token::InternedString;
41 use rustc_front::intravisit::Visitor;
42 use rustc_front::hir;
43 use log;
44
45 pub struct LocalCrateReader<'a, 'b:'a> {
46     sess: &'a Session,
47     cstore: &'a CStore,
48     creader: CrateReader<'a>,
49     ast_map: &'a hir_map::Map<'b>,
50 }
51
52 pub struct CrateReader<'a> {
53     sess: &'a Session,
54     cstore: &'a CStore,
55     next_crate_num: ast::CrateNum,
56     foreign_item_map: FnvHashMap<String, Vec<ast::NodeId>>,
57     local_crate_name: String,
58 }
59
60 impl<'a, 'b, 'hir> Visitor<'hir> for LocalCrateReader<'a, 'b> {
61     fn visit_item(&mut self, a: &'hir hir::Item) {
62         self.process_item(a);
63     }
64 }
65
66 fn dump_crates(cstore: &CStore) {
67     info!("resolved crates:");
68     cstore.iter_crate_data_origins(|_, data, opt_source| {
69         info!("  name: {}", data.name());
70         info!("  cnum: {}", data.cnum);
71         info!("  hash: {}", data.hash());
72         info!("  reqd: {}", data.explicitly_linked.get());
73         opt_source.map(|cs| {
74             let CrateSource { dylib, rlib, cnum: _ } = cs;
75             dylib.map(|dl| info!("  dylib: {}", dl.0.display()));
76             rlib.map(|rl|  info!("   rlib: {}", rl.0.display()));
77         });
78     })
79 }
80
81 fn should_link(i: &ast::Item) -> bool {
82     !attr::contains_name(&i.attrs, "no_link")
83 }
84 // Dup for the hir
85 fn should_link_hir(i: &hir::Item) -> bool {
86     !attr::contains_name(&i.attrs, "no_link")
87 }
88
89 struct CrateInfo {
90     ident: String,
91     name: String,
92     id: ast::NodeId,
93     should_link: bool,
94 }
95
96 fn register_native_lib(sess: &Session,
97                        cstore: &CStore,
98                        span: Option<Span>,
99                        name: String,
100                        kind: cstore::NativeLibraryKind) {
101     if name.is_empty() {
102         match span {
103             Some(span) => {
104                 span_err!(sess, span, E0454,
105                           "#[link(name = \"\")] given with 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) => {
118                 span_err!(sess, span, E0455,
119                           "{}", msg)
120             }
121             None => sess.err(msg),
122         }
123     }
124     cstore.add_used_library(name, kind);
125 }
126
127 // Extra info about a crate loaded for plugins or exported macros.
128 struct ExtensionCrate {
129     metadata: PMDSource,
130     dylib: Option<PathBuf>,
131     target_only: bool,
132 }
133
134 enum PMDSource {
135     Registered(Rc<cstore::crate_metadata>),
136     Owned(MetadataBlob),
137 }
138
139 impl PMDSource {
140     pub fn as_slice<'a>(&'a self) -> &'a [u8] {
141         match *self {
142             PMDSource::Registered(ref cmd) => cmd.data(),
143             PMDSource::Owned(ref mdb) => mdb.as_slice(),
144         }
145     }
146 }
147
148 impl<'a> CrateReader<'a> {
149     pub fn new(sess: &'a Session,
150                cstore: &'a CStore,
151                local_crate_name: &str) -> CrateReader<'a> {
152         CrateReader {
153             sess: sess,
154             cstore: cstore,
155             next_crate_num: cstore.next_crate_num(),
156             foreign_item_map: FnvHashMap(),
157             local_crate_name: local_crate_name.to_owned(),
158         }
159     }
160
161     fn extract_crate_info(&self, i: &ast::Item) -> Option<CrateInfo> {
162         match i.node {
163             ast::ItemKind::ExternCrate(ref path_opt) => {
164                 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
165                        i.ident, path_opt);
166                 let name = match *path_opt {
167                     Some(name) => {
168                         validate_crate_name(Some(self.sess), &name.as_str(),
169                                             Some(i.span));
170                         name.to_string()
171                     }
172                     None => i.ident.to_string(),
173                 };
174                 Some(CrateInfo {
175                     ident: i.ident.to_string(),
176                     name: name,
177                     id: i.id,
178                     should_link: should_link(i),
179                 })
180             }
181             _ => None
182         }
183     }
184
185     // Dup of the above, but for the hir
186     fn extract_crate_info_hir(&self, i: &hir::Item) -> Option<CrateInfo> {
187         match i.node {
188             hir::ItemExternCrate(ref path_opt) => {
189                 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
190                        i.name, path_opt);
191                 let name = match *path_opt {
192                     Some(name) => {
193                         validate_crate_name(Some(self.sess), &name.as_str(),
194                                             Some(i.span));
195                         name.to_string()
196                     }
197                     None => i.name.to_string(),
198                 };
199                 Some(CrateInfo {
200                     ident: i.name.to_string(),
201                     name: name,
202                     id: i.id,
203                     should_link: should_link_hir(i),
204                 })
205             }
206             _ => None
207         }
208     }
209
210     fn existing_match(&self, name: &str, hash: Option<&Svh>, kind: PathKind)
211                       -> Option<ast::CrateNum> {
212         let mut ret = None;
213         self.cstore.iter_crate_data(|cnum, data| {
214             if data.name != name { return }
215
216             match hash {
217                 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
218                 Some(..) => return,
219                 None => {}
220             }
221
222             // When the hash is None we're dealing with a top-level dependency
223             // in which case we may have a specification on the command line for
224             // this library. Even though an upstream library may have loaded
225             // something of the same name, we have to make sure it was loaded
226             // from the exact same location as well.
227             //
228             // We're also sure to compare *paths*, not actual byte slices. The
229             // `source` stores paths which are normalized which may be different
230             // from the strings on the command line.
231             let source = self.cstore.used_crate_source(cnum);
232             if let Some(locs) = self.sess.opts.externs.get(name) {
233                 let found = locs.iter().any(|l| {
234                     let l = fs::canonicalize(l).ok();
235                     source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
236                     source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
237                 });
238                 if found {
239                     ret = Some(cnum);
240                 }
241                 return
242             }
243
244             // Alright, so we've gotten this far which means that `data` has the
245             // right name, we don't have a hash, and we don't have a --extern
246             // pointing for ourselves. We're still not quite yet done because we
247             // have to make sure that this crate was found in the crate lookup
248             // path (this is a top-level dependency) as we don't want to
249             // implicitly load anything inside the dependency lookup path.
250             let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
251                                   .unwrap().1;
252             if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
253                 ret = Some(cnum);
254             }
255         });
256         return ret;
257     }
258
259     fn verify_rustc_version(&self,
260                             name: &str,
261                             span: Span,
262                             metadata: &MetadataBlob) {
263         let crate_rustc_version = decoder::crate_rustc_version(metadata.as_slice());
264         if crate_rustc_version != Some(rustc_version()) {
265             let mut err = struct_span_fatal!(self.sess, span, E0514,
266                                              "the crate `{}` has been compiled with {}, which is \
267                                               incompatible with this version of rustc",
268                                               name,
269                                               crate_rustc_version
270                                               .as_ref().map(|s| &**s)
271                                               .unwrap_or("an old version of rustc"));
272             err.fileline_help(span, "consider removing the compiled binaries and recompiling \
273                                      with your current version of rustc");
274             err.emit();
275         }
276     }
277
278     fn verify_no_symbol_conflicts(&self,
279                                   span: Span,
280                                   metadata: &MetadataBlob) {
281         let disambiguator = decoder::get_crate_disambiguator(metadata.as_slice());
282         let crate_name = decoder::get_crate_name(metadata.as_slice());
283
284         // Check for (potential) conflicts with the local crate
285         if self.local_crate_name == crate_name &&
286            self.sess.crate_disambiguator.get().as_str() == disambiguator {
287             span_fatal!(self.sess, span, E0519,
288                         "the current crate is indistinguishable from one of its \
289                          dependencies: it has the same crate-name `{}` and was \
290                          compiled with the same `-C metadata` arguments. This \
291                          will result in symbol conflicts between the two.",
292                         crate_name)
293         }
294
295         let svh = decoder::get_crate_hash(metadata.as_slice());
296         // Check for conflicts with any crate loaded so far
297         self.cstore.iter_crate_data(|_, other| {
298             if other.name() == crate_name && // same crate-name
299                other.disambiguator() == disambiguator &&  // same crate-disambiguator
300                other.hash() != svh { // but different SVH
301                 span_fatal!(self.sess, span, E0521,
302                         "found two different crates with name `{}` that are \
303                          not distinguished by differing `-C metadata`. This \
304                          will result in symbol conflicts between the two.",
305                         crate_name)
306             }
307         });
308     }
309
310     fn register_crate(&mut self,
311                       root: &Option<CratePaths>,
312                       ident: &str,
313                       name: &str,
314                       span: Span,
315                       lib: loader::Library,
316                       explicitly_linked: bool)
317                       -> (ast::CrateNum, Rc<cstore::crate_metadata>,
318                           cstore::CrateSource) {
319         self.verify_rustc_version(name, span, &lib.metadata);
320         self.verify_no_symbol_conflicts(span, &lib.metadata);
321
322         // Claim this crate number and cache it
323         let cnum = self.next_crate_num;
324         self.next_crate_num += 1;
325
326         // Stash paths for top-most crate locally if necessary.
327         let crate_paths = if root.is_none() {
328             Some(CratePaths {
329                 ident: ident.to_string(),
330                 dylib: lib.dylib.clone().map(|p| p.0),
331                 rlib:  lib.rlib.clone().map(|p| p.0),
332             })
333         } else {
334             None
335         };
336         // Maintain a reference to the top most crate.
337         let root = if root.is_some() { root } else { &crate_paths };
338
339         let loader::Library { dylib, rlib, metadata } = lib;
340
341         let cnum_map = self.resolve_crate_deps(root, metadata.as_slice(), span);
342         let staged_api = self.is_staged_api(metadata.as_slice());
343
344         let cmeta = Rc::new(cstore::crate_metadata {
345             name: name.to_string(),
346             extern_crate: Cell::new(None),
347             index: decoder::load_index(metadata.as_slice()),
348             xref_index: decoder::load_xrefs(metadata.as_slice()),
349             data: metadata,
350             cnum_map: RefCell::new(cnum_map),
351             cnum: cnum,
352             codemap_import_info: RefCell::new(vec![]),
353             staged_api: staged_api,
354             explicitly_linked: Cell::new(explicitly_linked),
355         });
356
357         let source = cstore::CrateSource {
358             dylib: dylib,
359             rlib: rlib,
360             cnum: cnum,
361         };
362
363         self.cstore.set_crate_data(cnum, cmeta.clone());
364         self.cstore.add_used_crate_source(source.clone());
365         (cnum, cmeta, source)
366     }
367
368     fn is_staged_api(&self, data: &[u8]) -> bool {
369         let attrs = decoder::get_crate_attributes(data);
370         for attr in &attrs {
371             if attr.name() == "stable" || attr.name() == "unstable" {
372                 return true
373             }
374         }
375         false
376     }
377
378     fn resolve_crate(&mut self,
379                      root: &Option<CratePaths>,
380                      ident: &str,
381                      name: &str,
382                      hash: Option<&Svh>,
383                      span: Span,
384                      kind: PathKind,
385                      explicitly_linked: bool)
386                      -> (ast::CrateNum, Rc<cstore::crate_metadata>, cstore::CrateSource) {
387         enum LookupResult {
388             Previous(ast::CrateNum),
389             Loaded(loader::Library),
390         }
391         let result = match self.existing_match(name, hash, kind) {
392             Some(cnum) => LookupResult::Previous(cnum),
393             None => {
394                 let mut load_ctxt = loader::Context {
395                     sess: self.sess,
396                     span: span,
397                     ident: ident,
398                     crate_name: name,
399                     hash: hash.map(|a| &*a),
400                     filesearch: self.sess.target_filesearch(kind),
401                     target: &self.sess.target.target,
402                     triple: &self.sess.opts.target_triple,
403                     root: root,
404                     rejected_via_hash: vec!(),
405                     rejected_via_triple: vec!(),
406                     rejected_via_kind: vec!(),
407                     should_match_name: true,
408                 };
409                 let library = load_ctxt.load_library_crate();
410
411                 // In the case that we're loading a crate, but not matching
412                 // against a hash, we could load a crate which has the same hash
413                 // as an already loaded crate. If this is the case prevent
414                 // duplicates by just using the first crate.
415                 let meta_hash = decoder::get_crate_hash(library.metadata
416                                                                .as_slice());
417                 let mut result = LookupResult::Loaded(library);
418                 self.cstore.iter_crate_data(|cnum, data| {
419                     if data.name() == name && meta_hash == data.hash() {
420                         assert!(hash.is_none());
421                         result = LookupResult::Previous(cnum);
422                     }
423                 });
424                 result
425             }
426         };
427
428         match result {
429             LookupResult::Previous(cnum) => {
430                 let data = self.cstore.get_crate_data(cnum);
431                 if explicitly_linked && !data.explicitly_linked.get() {
432                     data.explicitly_linked.set(explicitly_linked);
433                 }
434                 (cnum, data, self.cstore.used_crate_source(cnum))
435             }
436             LookupResult::Loaded(library) => {
437                 self.register_crate(root, ident, name, span, library,
438                                     explicitly_linked)
439             }
440         }
441     }
442
443     fn update_extern_crate(&mut self,
444                            cnum: ast::CrateNum,
445                            mut extern_crate: ExternCrate)
446     {
447         let cmeta = self.cstore.get_crate_data(cnum);
448         let old_extern_crate = cmeta.extern_crate.get();
449
450         // Prefer:
451         // - something over nothing (tuple.0);
452         // - direct extern crate to indirect (tuple.1);
453         // - shorter paths to longer (tuple.2).
454         let new_rank = (true, extern_crate.direct, !extern_crate.path_len);
455         let old_rank = match old_extern_crate {
456             None => (false, false, !0),
457             Some(ref c) => (true, c.direct, !c.path_len),
458         };
459
460         if old_rank >= new_rank {
461             return; // no change needed
462         }
463
464         cmeta.extern_crate.set(Some(extern_crate));
465
466         // Propagate the extern crate info to dependencies.
467         extern_crate.direct = false;
468         for &dep_cnum in cmeta.cnum_map.borrow().values() {
469             self.update_extern_crate(dep_cnum, extern_crate);
470         }
471     }
472
473     // Go through the crate metadata and load any crates that it references
474     fn resolve_crate_deps(&mut self,
475                           root: &Option<CratePaths>,
476                           cdata: &[u8],
477                           span : Span)
478                           -> cstore::cnum_map {
479         debug!("resolving deps of external crate");
480         // The map from crate numbers in the crate we're resolving to local crate
481         // numbers
482         decoder::get_crate_deps(cdata).iter().map(|dep| {
483             debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
484             let (local_cnum, _, _) = self.resolve_crate(root,
485                                                         &dep.name,
486                                                         &dep.name,
487                                                         Some(&dep.hash),
488                                                         span,
489                                                         PathKind::Dependency,
490                                                         dep.explicitly_linked);
491             (dep.cnum, local_cnum)
492         }).collect()
493     }
494
495     fn read_extension_crate(&mut self, span: Span, info: &CrateInfo) -> ExtensionCrate {
496         let target_triple = &self.sess.opts.target_triple[..];
497         let is_cross = target_triple != config::host_triple();
498         let mut should_link = info.should_link && !is_cross;
499         let mut target_only = false;
500         let ident = info.ident.clone();
501         let name = info.name.clone();
502         let mut load_ctxt = loader::Context {
503             sess: self.sess,
504             span: span,
505             ident: &ident[..],
506             crate_name: &name[..],
507             hash: None,
508             filesearch: self.sess.host_filesearch(PathKind::Crate),
509             target: &self.sess.host,
510             triple: config::host_triple(),
511             root: &None,
512             rejected_via_hash: vec!(),
513             rejected_via_triple: vec!(),
514             rejected_via_kind: vec!(),
515             should_match_name: true,
516         };
517         let library = match load_ctxt.maybe_load_library_crate() {
518             Some(l) => l,
519             None if is_cross => {
520                 // Try loading from target crates. This will abort later if we
521                 // try to load a plugin registrar function,
522                 target_only = true;
523                 should_link = info.should_link;
524
525                 load_ctxt.target = &self.sess.target.target;
526                 load_ctxt.triple = target_triple;
527                 load_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
528                 load_ctxt.load_library_crate()
529             }
530             None => { load_ctxt.report_load_errs(); unreachable!() },
531         };
532
533         let dylib = library.dylib.clone();
534         let register = should_link && self.existing_match(&info.name,
535                                                           None,
536                                                           PathKind::Crate).is_none();
537         let metadata = if register {
538             // Register crate now to avoid double-reading metadata
539             let (_, cmd, _) = self.register_crate(&None, &info.ident,
540                                                   &info.name, span, library,
541                                                   true);
542             PMDSource::Registered(cmd)
543         } else {
544             // Not registering the crate; just hold on to the metadata
545             PMDSource::Owned(library.metadata)
546         };
547
548         ExtensionCrate {
549             metadata: metadata,
550             dylib: dylib.map(|p| p.0),
551             target_only: target_only,
552         }
553     }
554
555     /// Read exported macros.
556     pub fn read_exported_macros(&mut self, item: &ast::Item) -> Vec<ast::MacroDef> {
557         let ci = self.extract_crate_info(item).unwrap();
558         let ekrate = self.read_extension_crate(item.span, &ci);
559
560         let source_name = format!("<{} macros>", item.ident);
561         let mut macros = vec![];
562         decoder::each_exported_macro(ekrate.metadata.as_slice(),
563                                      &self.cstore.intr,
564             |name, attrs, span, body| {
565                 // NB: Don't use parse::parse_tts_from_source_str because it parses with
566                 // quote_depth > 0.
567                 let mut p = parse::new_parser_from_source_str(&self.sess.parse_sess,
568                                                               self.sess.opts.cfg.clone(),
569                                                               source_name.clone(),
570                                                               body);
571                 let lo = p.span.lo;
572                 let body = match p.parse_all_token_trees() {
573                     Ok(body) => body,
574                     Err(mut err) => {
575                         err.emit();
576                         panic!(FatalError);
577                     }
578                 };
579                 let local_span = mk_sp(lo, p.last_span.hi);
580
581                 // Mark the attrs as used
582                 for attr in &attrs {
583                     attr::mark_used(attr);
584                 }
585
586                 macros.push(ast::MacroDef {
587                     ident: ast::Ident::with_empty_ctxt(name),
588                     attrs: attrs,
589                     id: ast::DUMMY_NODE_ID,
590                     span: local_span,
591                     imported_from: Some(item.ident),
592                     // overridden in plugin/load.rs
593                     export: false,
594                     use_locally: false,
595                     allow_internal_unstable: false,
596
597                     body: body,
598                 });
599                 self.sess.imported_macro_spans.borrow_mut()
600                     .insert(local_span, (name.as_str().to_string(), span));
601                 true
602             }
603         );
604         macros
605     }
606
607     /// Look for a plugin registrar. Returns library path and symbol name.
608     pub fn find_plugin_registrar(&mut self, span: Span, name: &str)
609                                  -> Option<(PathBuf, String)> {
610         let ekrate = self.read_extension_crate(span, &CrateInfo {
611              name: name.to_string(),
612              ident: name.to_string(),
613              id: ast::DUMMY_NODE_ID,
614              should_link: false,
615         });
616
617         if ekrate.target_only {
618             // Need to abort before syntax expansion.
619             let message = format!("plugin `{}` is not available for triple `{}` \
620                                    (only found {})",
621                                   name,
622                                   config::host_triple(),
623                                   self.sess.opts.target_triple);
624             span_fatal!(self.sess, span, E0456, "{}", &message[..]);
625         }
626
627         let registrar =
628             decoder::get_plugin_registrar_fn(ekrate.metadata.as_slice())
629             .map(|id| decoder::get_symbol_from_buf(ekrate.metadata.as_slice(), id));
630
631         match (ekrate.dylib.as_ref(), registrar) {
632             (Some(dylib), Some(reg)) => Some((dylib.to_path_buf(), reg)),
633             (None, Some(_)) => {
634                 span_err!(self.sess, span, E0457,
635                           "plugin `{}` only found in rlib format, but must be available \
636                            in dylib format",
637                           name);
638                 // No need to abort because the loading code will just ignore this
639                 // empty dylib.
640                 None
641             }
642             _ => None,
643         }
644     }
645
646     fn register_statically_included_foreign_items(&mut self) {
647         let libs = self.cstore.get_used_libraries();
648         for (lib, list) in self.foreign_item_map.iter() {
649             let is_static = libs.borrow().iter().any(|&(ref name, kind)| {
650                 lib == name && kind == cstore::NativeStatic
651             });
652             if is_static {
653                 for id in list {
654                     self.cstore.add_statically_included_foreign_item(*id);
655                 }
656             }
657         }
658     }
659
660     fn inject_allocator_crate(&mut self) {
661         // Make sure that we actually need an allocator, if none of our
662         // dependencies need one then we definitely don't!
663         //
664         // Also, if one of our dependencies has an explicit allocator, then we
665         // also bail out as we don't need to implicitly inject one.
666         let mut needs_allocator = false;
667         let mut found_required_allocator = false;
668         self.cstore.iter_crate_data(|cnum, data| {
669             needs_allocator = needs_allocator || data.needs_allocator();
670             if data.is_allocator() {
671                 debug!("{} required by rlib and is an allocator", data.name());
672                 self.inject_allocator_dependency(cnum);
673                 found_required_allocator = found_required_allocator ||
674                     data.explicitly_linked.get();
675             }
676         });
677         if !needs_allocator || found_required_allocator { return }
678
679         // At this point we've determined that we need an allocator and no
680         // previous allocator has been activated. We look through our outputs of
681         // crate types to see what kind of allocator types we may need.
682         //
683         // The main special output type here is that rlibs do **not** need an
684         // allocator linked in (they're just object files), only final products
685         // (exes, dylibs, staticlibs) need allocators.
686         let mut need_lib_alloc = false;
687         let mut need_exe_alloc = false;
688         for ct in self.sess.crate_types.borrow().iter() {
689             match *ct {
690                 config::CrateTypeExecutable => need_exe_alloc = true,
691                 config::CrateTypeDylib |
692                 config::CrateTypeStaticlib => need_lib_alloc = true,
693                 config::CrateTypeRlib => {}
694             }
695         }
696         if !need_lib_alloc && !need_exe_alloc { return }
697
698         // The default allocator crate comes from the custom target spec, and we
699         // choose between the standard library allocator or exe allocator. This
700         // distinction exists because the default allocator for binaries (where
701         // the world is Rust) is different than library (where the world is
702         // likely *not* Rust).
703         //
704         // If a library is being produced, but we're also flagged with `-C
705         // prefer-dynamic`, then we interpret this as a *Rust* dynamic library
706         // is being produced so we use the exe allocator instead.
707         //
708         // What this boils down to is:
709         //
710         // * Binaries use jemalloc
711         // * Staticlibs and Rust dylibs use system malloc
712         // * Rust dylibs used as dependencies to rust use jemalloc
713         let name = if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
714             &self.sess.target.target.options.lib_allocation_crate
715         } else {
716             &self.sess.target.target.options.exe_allocation_crate
717         };
718         let (cnum, data, _) = self.resolve_crate(&None, name, name, None,
719                                                  codemap::DUMMY_SP,
720                                                  PathKind::Crate, false);
721
722         // To ensure that the `-Z allocation-crate=foo` option isn't abused, and
723         // to ensure that the allocator is indeed an allocator, we verify that
724         // the crate loaded here is indeed tagged #![allocator].
725         if !data.is_allocator() {
726             self.sess.err(&format!("the allocator crate `{}` is not tagged \
727                                     with #![allocator]", data.name()));
728         }
729
730         self.sess.injected_allocator.set(Some(cnum));
731         self.inject_allocator_dependency(cnum);
732     }
733
734     fn inject_allocator_dependency(&self, allocator: ast::CrateNum) {
735         // Before we inject any dependencies, make sure we don't inject a
736         // circular dependency by validating that this allocator crate doesn't
737         // transitively depend on any `#![needs_allocator]` crates.
738         validate(self, allocator, allocator);
739
740         // All crates tagged with `needs_allocator` do not explicitly depend on
741         // the allocator selected for this compile, but in order for this
742         // compilation to be successfully linked we need to inject a dependency
743         // (to order the crates on the command line correctly).
744         //
745         // Here we inject a dependency from all crates with #![needs_allocator]
746         // to the crate tagged with #![allocator] for this compilation unit.
747         self.cstore.iter_crate_data(|cnum, data| {
748             if !data.needs_allocator() {
749                 return
750             }
751
752             info!("injecting a dep from {} to {}", cnum, allocator);
753             let mut cnum_map = data.cnum_map.borrow_mut();
754             let remote_cnum = cnum_map.len() + 1;
755             let prev = cnum_map.insert(remote_cnum as ast::CrateNum, allocator);
756             assert!(prev.is_none());
757         });
758
759         fn validate(me: &CrateReader, krate: ast::CrateNum,
760                     allocator: ast::CrateNum) {
761             let data = me.cstore.get_crate_data(krate);
762             if data.needs_allocator() {
763                 let krate_name = data.name();
764                 let data = me.cstore.get_crate_data(allocator);
765                 let alloc_name = data.name();
766                 me.sess.err(&format!("the allocator crate `{}` cannot depend \
767                                       on a crate that needs an allocator, but \
768                                       it depends on `{}`", alloc_name,
769                                       krate_name));
770             }
771
772             for (_, &dep) in data.cnum_map.borrow().iter() {
773                 validate(me, dep, allocator);
774             }
775         }
776     }
777 }
778
779 impl<'a, 'b> LocalCrateReader<'a, 'b> {
780     pub fn new(sess: &'a Session,
781                cstore: &'a CStore,
782                map: &'a hir_map::Map<'b>,
783                local_crate_name: &str)
784                -> LocalCrateReader<'a, 'b> {
785         LocalCrateReader {
786             sess: sess,
787             cstore: cstore,
788             creader: CrateReader::new(sess, cstore, local_crate_name),
789             ast_map: map,
790         }
791     }
792
793     // Traverses an AST, reading all the information about use'd crates and
794     // extern libraries necessary for later resolving, typechecking, linking,
795     // etc.
796     pub fn read_crates(&mut self) {
797         let _task = self.ast_map.dep_graph.in_task(DepNode::CrateReader);
798         let krate = self.ast_map.krate();
799
800         self.process_crate(krate);
801         krate.visit_all_items(self);
802         self.creader.inject_allocator_crate();
803
804         if log_enabled!(log::INFO) {
805             dump_crates(&self.cstore);
806         }
807
808         for &(ref name, kind) in &self.sess.opts.libs {
809             register_native_lib(self.sess, self.cstore, None, name.clone(), kind);
810         }
811         self.creader.register_statically_included_foreign_items();
812     }
813
814     fn process_crate(&self, c: &hir::Crate) {
815         for a in c.attrs.iter().filter(|m| m.name() == "link_args") {
816             match a.value_str() {
817                 Some(ref linkarg) => self.cstore.add_used_link_args(&linkarg),
818                 None => { /* fallthrough */ }
819             }
820         }
821     }
822
823     fn process_item(&mut self, i: &hir::Item) {
824         match i.node {
825             hir::ItemExternCrate(_) => {
826                 if !should_link_hir(i) {
827                     return;
828                 }
829
830                 match self.creader.extract_crate_info_hir(i) {
831                     Some(info) => {
832                         let (cnum, _, _) = self.creader.resolve_crate(&None,
833                                                                           &info.ident,
834                                                                           &info.name,
835                                                                           None,
836                                                                           i.span,
837                                                                           PathKind::Crate,
838                                                                           true);
839                         let def_id = self.ast_map.local_def_id(i.id);
840
841                         let len = self.ast_map.def_path(def_id).data.len();
842
843                         self.creader.update_extern_crate(cnum,
844                                                          ExternCrate {
845                                                              def_id: def_id,
846                                                              span: i.span,
847                                                              direct: true,
848                                                              path_len: len,
849                                                          });
850                         self.cstore.add_extern_mod_stmt_cnum(info.id, cnum);
851                     }
852                     None => ()
853                 }
854             }
855             hir::ItemForeignMod(ref fm) => self.process_foreign_mod(i, fm),
856             _ => { }
857         }
858     }
859
860     fn process_foreign_mod(&mut self, i: &hir::Item, fm: &hir::ForeignMod) {
861         if fm.abi == Abi::Rust || fm.abi == Abi::RustIntrinsic || fm.abi == Abi::PlatformIntrinsic {
862             return;
863         }
864
865         // First, add all of the custom #[link_args] attributes
866         for m in i.attrs.iter().filter(|a| a.check_name("link_args")) {
867             if let Some(linkarg) = m.value_str() {
868                 self.cstore.add_used_link_args(&linkarg);
869             }
870         }
871
872         // Next, process all of the #[link(..)]-style arguments
873         for m in i.attrs.iter().filter(|a| a.check_name("link")) {
874             let items = match m.meta_item_list() {
875                 Some(item) => item,
876                 None => continue,
877             };
878             let kind = items.iter().find(|k| {
879                 k.check_name("kind")
880             }).and_then(|a| a.value_str());
881             let kind = match kind.as_ref().map(|s| &s[..]) {
882                 Some("static") => cstore::NativeStatic,
883                 Some("dylib") => cstore::NativeUnknown,
884                 Some("framework") => cstore::NativeFramework,
885                 Some(k) => {
886                     span_err!(self.sess, m.span, E0458,
887                               "unknown kind: `{}`", k);
888                     cstore::NativeUnknown
889                 }
890                 None => cstore::NativeUnknown
891             };
892             let n = items.iter().find(|n| {
893                 n.check_name("name")
894             }).and_then(|a| a.value_str());
895             let n = match n {
896                 Some(n) => n,
897                 None => {
898                     span_err!(self.sess, m.span, E0459,
899                               "#[link(...)] specified without `name = \"foo\"`");
900                     InternedString::new("foo")
901                 }
902             };
903             register_native_lib(self.sess, self.cstore, Some(m.span), n.to_string(), kind);
904         }
905
906         // Finally, process the #[linked_from = "..."] attribute
907         for m in i.attrs.iter().filter(|a| a.check_name("linked_from")) {
908             let lib_name = match m.value_str() {
909                 Some(name) => name,
910                 None => continue,
911             };
912             let list = self.creader.foreign_item_map.entry(lib_name.to_string())
913                                                     .or_insert(Vec::new());
914             list.extend(fm.items.iter().map(|it| it.id));
915         }
916     }
917 }
918
919 /// Imports the codemap from an external crate into the codemap of the crate
920 /// currently being compiled (the "local crate").
921 ///
922 /// The import algorithm works analogous to how AST items are inlined from an
923 /// external crate's metadata:
924 /// For every FileMap in the external codemap an 'inline' copy is created in the
925 /// local codemap. The correspondence relation between external and local
926 /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
927 /// function. When an item from an external crate is later inlined into this
928 /// crate, this correspondence information is used to translate the span
929 /// information of the inlined item so that it refers the correct positions in
930 /// the local codemap (see `astencode::DecodeContext::tr_span()`).
931 ///
932 /// The import algorithm in the function below will reuse FileMaps already
933 /// existing in the local codemap. For example, even if the FileMap of some
934 /// source file of libstd gets imported many times, there will only ever be
935 /// one FileMap object for the corresponding file in the local codemap.
936 ///
937 /// Note that imported FileMaps do not actually contain the source code of the
938 /// file they represent, just information about length, line breaks, and
939 /// multibyte characters. This information is enough to generate valid debuginfo
940 /// for items inlined from other crates.
941 pub fn import_codemap(local_codemap: &codemap::CodeMap,
942                       metadata: &MetadataBlob)
943                       -> Vec<cstore::ImportedFileMap> {
944     let external_codemap = decoder::get_imported_filemaps(metadata.as_slice());
945
946     let imported_filemaps = external_codemap.into_iter().map(|filemap_to_import| {
947         // Try to find an existing FileMap that can be reused for the filemap to
948         // be imported. A FileMap is reusable if it is exactly the same, just
949         // positioned at a different offset within the codemap.
950         let reusable_filemap = {
951             local_codemap.files
952                          .borrow()
953                          .iter()
954                          .find(|fm| are_equal_modulo_startpos(&fm, &filemap_to_import))
955                          .map(|rc| rc.clone())
956         };
957
958         match reusable_filemap {
959             Some(fm) => {
960                 cstore::ImportedFileMap {
961                     original_start_pos: filemap_to_import.start_pos,
962                     original_end_pos: filemap_to_import.end_pos,
963                     translated_filemap: fm
964                 }
965             }
966             None => {
967                 // We can't reuse an existing FileMap, so allocate a new one
968                 // containing the information we need.
969                 let codemap::FileMap {
970                     name,
971                     start_pos,
972                     end_pos,
973                     lines,
974                     multibyte_chars,
975                     ..
976                 } = filemap_to_import;
977
978                 let source_length = (end_pos - start_pos).to_usize();
979
980                 // Translate line-start positions and multibyte character
981                 // position into frame of reference local to file.
982                 // `CodeMap::new_imported_filemap()` will then translate those
983                 // coordinates to their new global frame of reference when the
984                 // offset of the FileMap is known.
985                 let mut lines = lines.into_inner();
986                 for pos in &mut lines {
987                     *pos = *pos - start_pos;
988                 }
989                 let mut multibyte_chars = multibyte_chars.into_inner();
990                 for mbc in &mut multibyte_chars {
991                     mbc.pos = mbc.pos - start_pos;
992                 }
993
994                 let local_version = local_codemap.new_imported_filemap(name,
995                                                                        source_length,
996                                                                        lines,
997                                                                        multibyte_chars);
998                 cstore::ImportedFileMap {
999                     original_start_pos: start_pos,
1000                     original_end_pos: end_pos,
1001                     translated_filemap: local_version
1002                 }
1003             }
1004         }
1005     }).collect();
1006
1007     return imported_filemaps;
1008
1009     fn are_equal_modulo_startpos(fm1: &codemap::FileMap,
1010                                  fm2: &codemap::FileMap)
1011                                  -> bool {
1012         if fm1.name != fm2.name {
1013             return false;
1014         }
1015
1016         let lines1 = fm1.lines.borrow();
1017         let lines2 = fm2.lines.borrow();
1018
1019         if lines1.len() != lines2.len() {
1020             return false;
1021         }
1022
1023         for (&line1, &line2) in lines1.iter().zip(lines2.iter()) {
1024             if (line1 - fm1.start_pos) != (line2 - fm2.start_pos) {
1025                 return false;
1026             }
1027         }
1028
1029         let multibytes1 = fm1.multibyte_chars.borrow();
1030         let multibytes2 = fm2.multibyte_chars.borrow();
1031
1032         if multibytes1.len() != multibytes2.len() {
1033             return false;
1034         }
1035
1036         for (mb1, mb2) in multibytes1.iter().zip(multibytes2.iter()) {
1037             if (mb1.bytes != mb2.bytes) ||
1038                ((mb1.pos - fm1.start_pos) != (mb2.pos - fm2.start_pos)) {
1039                 return false;
1040             }
1041         }
1042
1043         true
1044     }
1045 }