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