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