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