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