]> git.lizzy.rs Git - rust.git/blob - src/librustc/metadata/creader.rs
9acd13f0a043906cc9e14e2e8a700705e00085e9
[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::cstore;
19 use metadata::cstore::{CStore, CrateSource, MetadataBlob};
20 use metadata::decoder;
21 use metadata::loader;
22 use metadata::loader::CratePaths;
23 use util::nodemap::FnvHashMap;
24 use front::map as hir_map;
25
26 use std::cell::{RefCell, Cell};
27 use std::path::PathBuf;
28 use std::rc::Rc;
29 use std::fs;
30
31 use syntax::ast;
32 use syntax::abi;
33 use syntax::codemap::{self, Span, mk_sp, Pos};
34 use syntax::parse;
35 use syntax::attr;
36 use syntax::attr::AttrMetaMethods;
37 use syntax::parse::token::InternedString;
38 use syntax::util::small_vector::SmallVector;
39 use rustc_front::visit;
40 use rustc_front::hir;
41 use log;
42
43 pub struct LocalCrateReader<'a, 'b:'a> {
44     sess: &'a Session,
45     creader: CrateReader<'a>,
46     ast_map: &'a hir_map::Map<'b>,
47 }
48
49 pub struct CrateReader<'a> {
50     sess: &'a Session,
51     next_crate_num: ast::CrateNum,
52     foreign_item_map: FnvHashMap<String, Vec<ast::NodeId>>,
53 }
54
55 impl<'a, 'b, 'v> visit::Visitor<'v> for LocalCrateReader<'a, 'b> {
56     fn visit_item(&mut self, a: &hir::Item) {
57         self.process_item(a);
58         visit::walk_item(self, 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 register_crate(&mut self,
274                       root: &Option<CratePaths>,
275                       ident: &str,
276                       name: &str,
277                       span: Span,
278                       lib: loader::Library,
279                       explicitly_linked: bool)
280                       -> (ast::CrateNum, Rc<cstore::crate_metadata>,
281                           cstore::CrateSource) {
282         // Claim this crate number and cache it
283         let cnum = self.next_crate_num;
284         self.next_crate_num += 1;
285
286         // Stash paths for top-most crate locally if necessary.
287         let crate_paths = if root.is_none() {
288             Some(CratePaths {
289                 ident: ident.to_string(),
290                 dylib: lib.dylib.clone().map(|p| p.0),
291                 rlib:  lib.rlib.clone().map(|p| p.0),
292             })
293         } else {
294             None
295         };
296         // Maintain a reference to the top most crate.
297         let root = if root.is_some() { root } else { &crate_paths };
298
299         let loader::Library { dylib, rlib, metadata } = lib;
300
301         let cnum_map = self.resolve_crate_deps(root, metadata.as_slice(), span);
302         let staged_api = self.is_staged_api(metadata.as_slice());
303
304         let cmeta = Rc::new(cstore::crate_metadata {
305             name: name.to_string(),
306             local_path: RefCell::new(SmallVector::zero()),
307             index: decoder::load_index(metadata.as_slice()),
308             data: metadata,
309             cnum_map: RefCell::new(cnum_map),
310             cnum: cnum,
311             codemap_import_info: RefCell::new(vec![]),
312             span: span,
313             staged_api: staged_api,
314             explicitly_linked: Cell::new(explicitly_linked),
315         });
316
317         let source = cstore::CrateSource {
318             dylib: dylib,
319             rlib: rlib,
320             cnum: cnum,
321         };
322
323         self.sess.cstore.set_crate_data(cnum, cmeta.clone());
324         self.sess.cstore.add_used_crate_source(source.clone());
325         (cnum, cmeta, source)
326     }
327
328     fn is_staged_api(&self, data: &[u8]) -> bool {
329         let attrs = decoder::get_crate_attributes(data);
330         for attr in &attrs {
331             if &attr.name()[..] == "staged_api" {
332                 match attr.node.value.node { ast::MetaWord(_) => return true, _ => (/*pass*/) }
333             }
334         }
335
336         return false;
337     }
338
339     fn resolve_crate(&mut self,
340                      root: &Option<CratePaths>,
341                      ident: &str,
342                      name: &str,
343                      hash: Option<&Svh>,
344                      span: Span,
345                      kind: PathKind,
346                      explicitly_linked: bool)
347                          -> (ast::CrateNum, Rc<cstore::crate_metadata>,
348                              cstore::CrateSource) {
349         match self.existing_match(name, hash, kind) {
350             None => {
351                 let mut load_ctxt = loader::Context {
352                     sess: self.sess,
353                     span: span,
354                     ident: ident,
355                     crate_name: name,
356                     hash: hash.map(|a| &*a),
357                     filesearch: self.sess.target_filesearch(kind),
358                     target: &self.sess.target.target,
359                     triple: &self.sess.opts.target_triple,
360                     root: root,
361                     rejected_via_hash: vec!(),
362                     rejected_via_triple: vec!(),
363                     rejected_via_kind: vec!(),
364                     should_match_name: true,
365                 };
366                 let library = load_ctxt.load_library_crate();
367                 self.register_crate(root, ident, name, span, library,
368                                     explicitly_linked)
369             }
370             Some(cnum) => {
371                 let data = self.sess.cstore.get_crate_data(cnum);
372                 if explicitly_linked && !data.explicitly_linked.get() {
373                     data.explicitly_linked.set(explicitly_linked);
374                 }
375                 (cnum, data, self.sess.cstore.get_used_crate_source(cnum).unwrap())
376             }
377         }
378     }
379
380     // Go through the crate metadata and load any crates that it references
381     fn resolve_crate_deps(&mut self,
382                           root: &Option<CratePaths>,
383                           cdata: &[u8], span : Span)
384                        -> cstore::cnum_map {
385         debug!("resolving deps of external crate");
386         // The map from crate numbers in the crate we're resolving to local crate
387         // numbers
388         decoder::get_crate_deps(cdata).iter().map(|dep| {
389             debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
390             let (local_cnum, _, _) = self.resolve_crate(root,
391                                                    &dep.name,
392                                                    &dep.name,
393                                                    Some(&dep.hash),
394                                                    span,
395                                                    PathKind::Dependency,
396                                                    dep.explicitly_linked);
397             (dep.cnum, local_cnum)
398         }).collect()
399     }
400
401     fn read_extension_crate(&mut self, span: Span, info: &CrateInfo) -> ExtensionCrate {
402         let target_triple = &self.sess.opts.target_triple[..];
403         let is_cross = target_triple != config::host_triple();
404         let mut should_link = info.should_link && !is_cross;
405         let mut target_only = false;
406         let ident = info.ident.clone();
407         let name = info.name.clone();
408         let mut load_ctxt = loader::Context {
409             sess: self.sess,
410             span: span,
411             ident: &ident[..],
412             crate_name: &name[..],
413             hash: None,
414             filesearch: self.sess.host_filesearch(PathKind::Crate),
415             target: &self.sess.host,
416             triple: config::host_triple(),
417             root: &None,
418             rejected_via_hash: vec!(),
419             rejected_via_triple: vec!(),
420             rejected_via_kind: vec!(),
421             should_match_name: true,
422         };
423         let library = match load_ctxt.maybe_load_library_crate() {
424             Some(l) => l,
425             None if is_cross => {
426                 // Try loading from target crates. This will abort later if we
427                 // try to load a plugin registrar function,
428                 target_only = true;
429                 should_link = info.should_link;
430
431                 load_ctxt.target = &self.sess.target.target;
432                 load_ctxt.triple = target_triple;
433                 load_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
434                 load_ctxt.load_library_crate()
435             }
436             None => { load_ctxt.report_load_errs(); unreachable!() },
437         };
438
439         let dylib = library.dylib.clone();
440         let register = should_link && self.existing_match(&info.name,
441                                                           None,
442                                                           PathKind::Crate).is_none();
443         let metadata = if register {
444             // Register crate now to avoid double-reading metadata
445             let (_, cmd, _) = self.register_crate(&None, &info.ident,
446                                                   &info.name, span, library,
447                                                   true);
448             PMDSource::Registered(cmd)
449         } else {
450             // Not registering the crate; just hold on to the metadata
451             PMDSource::Owned(library.metadata)
452         };
453
454         ExtensionCrate {
455             metadata: metadata,
456             dylib: dylib.map(|p| p.0),
457             target_only: target_only,
458         }
459     }
460
461     /// Read exported macros.
462     pub fn read_exported_macros(&mut self, item: &ast::Item) -> Vec<ast::MacroDef> {
463         let ci = self.extract_crate_info(item).unwrap();
464         let ekrate = self.read_extension_crate(item.span, &ci);
465
466         let source_name = format!("<{} macros>", item.ident);
467         let mut macros = vec![];
468         decoder::each_exported_macro(ekrate.metadata.as_slice(),
469                                      &*self.sess.cstore.intr,
470             |name, attrs, body| {
471                 // NB: Don't use parse::parse_tts_from_source_str because it parses with
472                 // quote_depth > 0.
473                 let mut p = parse::new_parser_from_source_str(&self.sess.parse_sess,
474                                                               self.sess.opts.cfg.clone(),
475                                                               source_name.clone(),
476                                                               body);
477                 let lo = p.span.lo;
478                 let body = match p.parse_all_token_trees() {
479                     Ok(body) => body,
480                     Err(err) => panic!(err),
481                 };
482                 let span = mk_sp(lo, p.last_span.hi);
483                 p.abort_if_errors();
484                 macros.push(ast::MacroDef {
485                     ident: ast::Ident::with_empty_ctxt(name),
486                     attrs: attrs,
487                     id: ast::DUMMY_NODE_ID,
488                     span: span,
489                     imported_from: Some(item.ident),
490                     // overridden in plugin/load.rs
491                     export: false,
492                     use_locally: false,
493                     allow_internal_unstable: false,
494
495                     body: body,
496                 });
497                 true
498             }
499         );
500         macros
501     }
502
503     /// Look for a plugin registrar. Returns library path and symbol name.
504     pub fn find_plugin_registrar(&mut self, span: Span, name: &str)
505                                  -> Option<(PathBuf, String)> {
506         let ekrate = self.read_extension_crate(span, &CrateInfo {
507              name: name.to_string(),
508              ident: name.to_string(),
509              id: ast::DUMMY_NODE_ID,
510              should_link: false,
511         });
512
513         if ekrate.target_only {
514             // Need to abort before syntax expansion.
515             let message = format!("plugin `{}` is not available for triple `{}` \
516                                    (only found {})",
517                                   name,
518                                   config::host_triple(),
519                                   self.sess.opts.target_triple);
520             span_err!(self.sess, span, E0456, "{}", &message[..]);
521             self.sess.abort_if_errors();
522         }
523
524         let registrar = decoder::get_plugin_registrar_fn(ekrate.metadata.as_slice())
525             .map(|id| decoder::get_symbol_from_buf(ekrate.metadata.as_slice(), id));
526
527         match (ekrate.dylib.as_ref(), registrar) {
528             (Some(dylib), Some(reg)) => Some((dylib.to_path_buf(), reg)),
529             (None, Some(_)) => {
530                 span_err!(self.sess, span, E0457,
531                           "plugin `{}` only found in rlib format, but must be available \
532                            in dylib format",
533                           name);
534                 // No need to abort because the loading code will just ignore this
535                 // empty dylib.
536                 None
537             }
538             _ => None,
539         }
540     }
541
542     fn register_statically_included_foreign_items(&mut self) {
543         let libs = self.sess.cstore.get_used_libraries();
544         for (lib, list) in self.foreign_item_map.iter() {
545             let is_static = libs.borrow().iter().any(|&(ref name, kind)| {
546                 lib == name && kind == cstore::NativeStatic
547             });
548             if is_static {
549                 for id in list {
550                     self.sess.cstore.add_statically_included_foreign_item(*id);
551                 }
552             }
553         }
554     }
555
556     fn inject_allocator_crate(&mut self) {
557         // Make sure that we actually need an allocator, if none of our
558         // dependencies need one then we definitely don't!
559         //
560         // Also, if one of our dependencies has an explicit allocator, then we
561         // also bail out as we don't need to implicitly inject one.
562         let mut needs_allocator = false;
563         let mut found_required_allocator = false;
564         self.sess.cstore.iter_crate_data(|cnum, data| {
565             needs_allocator = needs_allocator || data.needs_allocator();
566             if data.is_allocator() {
567                 debug!("{} required by rlib and is an allocator", data.name());
568                 self.inject_allocator_dependency(cnum);
569                 found_required_allocator = found_required_allocator ||
570                     data.explicitly_linked.get();
571             }
572         });
573         if !needs_allocator || found_required_allocator { return }
574
575         // At this point we've determined that we need an allocator and no
576         // previous allocator has been activated. We look through our outputs of
577         // crate types to see what kind of allocator types we may need.
578         //
579         // The main special output type here is that rlibs do **not** need an
580         // allocator linked in (they're just object files), only final products
581         // (exes, dylibs, staticlibs) need allocators.
582         let mut need_lib_alloc = false;
583         let mut need_exe_alloc = false;
584         for ct in self.sess.crate_types.borrow().iter() {
585             match *ct {
586                 config::CrateTypeExecutable => need_exe_alloc = true,
587                 config::CrateTypeDylib |
588                 config::CrateTypeStaticlib => need_lib_alloc = true,
589                 config::CrateTypeRlib => {}
590             }
591         }
592         if !need_lib_alloc && !need_exe_alloc { return }
593
594         // The default allocator crate comes from the custom target spec, and we
595         // choose between the standard library allocator or exe allocator. This
596         // distinction exists because the default allocator for binaries (where
597         // the world is Rust) is different than library (where the world is
598         // likely *not* Rust).
599         //
600         // If a library is being produced, but we're also flagged with `-C
601         // prefer-dynamic`, then we interpret this as a *Rust* dynamic library
602         // is being produced so we use the exe allocator instead.
603         //
604         // What this boils down to is:
605         //
606         // * Binaries use jemalloc
607         // * Staticlibs and Rust dylibs use system malloc
608         // * Rust dylibs used as dependencies to rust use jemalloc
609         let name = if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
610             &self.sess.target.target.options.lib_allocation_crate
611         } else {
612             &self.sess.target.target.options.exe_allocation_crate
613         };
614         let (cnum, data, _) = self.resolve_crate(&None, name, name, None,
615                                                  codemap::DUMMY_SP,
616                                                  PathKind::Crate, false);
617
618         // To ensure that the `-Z allocation-crate=foo` option isn't abused, and
619         // to ensure that the allocator is indeed an allocator, we verify that
620         // the crate loaded here is indeed tagged #![allocator].
621         if !data.is_allocator() {
622             self.sess.err(&format!("the allocator crate `{}` is not tagged \
623                                     with #![allocator]", data.name()));
624         }
625
626         self.sess.injected_allocator.set(Some(cnum));
627         self.inject_allocator_dependency(cnum);
628     }
629
630     fn inject_allocator_dependency(&self, allocator: ast::CrateNum) {
631         // Before we inject any dependencies, make sure we don't inject a
632         // circular dependency by validating that this allocator crate doesn't
633         // transitively depend on any `#![needs_allocator]` crates.
634         validate(self, allocator, allocator);
635
636         // All crates tagged with `needs_allocator` do not explicitly depend on
637         // the allocator selected for this compile, but in order for this
638         // compilation to be successfully linked we need to inject a dependency
639         // (to order the crates on the command line correctly).
640         //
641         // Here we inject a dependency from all crates with #![needs_allocator]
642         // to the crate tagged with #![allocator] for this compilation unit.
643         self.sess.cstore.iter_crate_data(|cnum, data| {
644             if !data.needs_allocator() {
645                 return
646             }
647
648             info!("injecting a dep from {} to {}", cnum, allocator);
649             let mut cnum_map = data.cnum_map.borrow_mut();
650             let remote_cnum = cnum_map.len() + 1;
651             let prev = cnum_map.insert(remote_cnum as ast::CrateNum, allocator);
652             assert!(prev.is_none());
653         });
654
655         fn validate(me: &CrateReader, krate: ast::CrateNum,
656                     allocator: ast::CrateNum) {
657             let data = me.sess.cstore.get_crate_data(krate);
658             if data.needs_allocator() {
659                 let krate_name = data.name();
660                 let data = me.sess.cstore.get_crate_data(allocator);
661                 let alloc_name = data.name();
662                 me.sess.err(&format!("the allocator crate `{}` cannot depend \
663                                       on a crate that needs an allocator, but \
664                                       it depends on `{}`", alloc_name,
665                                       krate_name));
666             }
667
668             for (_, &dep) in data.cnum_map.borrow().iter() {
669                 validate(me, dep, allocator);
670             }
671         }
672     }
673 }
674
675 impl<'a, 'b> LocalCrateReader<'a, 'b> {
676     pub fn new(sess: &'a Session, map: &'a hir_map::Map<'b>) -> LocalCrateReader<'a, 'b> {
677         LocalCrateReader {
678             sess: sess,
679             creader: CrateReader::new(sess),
680             ast_map: map,
681         }
682     }
683
684     // Traverses an AST, reading all the information about use'd crates and
685     // extern libraries necessary for later resolving, typechecking, linking,
686     // etc.
687     pub fn read_crates(&mut self, krate: &hir::Crate) {
688         self.process_crate(krate);
689         visit::walk_crate(self, krate);
690         self.creader.inject_allocator_crate();
691
692         if log_enabled!(log::INFO) {
693             dump_crates(&self.sess.cstore);
694         }
695
696         for &(ref name, kind) in &self.sess.opts.libs {
697             register_native_lib(self.sess, None, name.clone(), kind);
698         }
699         self.creader.register_statically_included_foreign_items();
700     }
701
702     fn process_crate(&self, c: &hir::Crate) {
703         for a in c.attrs.iter().filter(|m| m.name() == "link_args") {
704             match a.value_str() {
705                 Some(ref linkarg) => self.sess.cstore.add_used_link_args(&linkarg),
706                 None => { /* fallthrough */ }
707             }
708         }
709     }
710
711     fn process_item(&mut self, i: &hir::Item) {
712         match i.node {
713             hir::ItemExternCrate(_) => {
714                 if !should_link_hir(i) {
715                     return;
716                 }
717
718                 match self.creader.extract_crate_info_hir(i) {
719                     Some(info) => {
720                         let (cnum, cmeta, _) = self.creader.resolve_crate(&None,
721                                                               &info.ident,
722                                                               &info.name,
723                                                               None,
724                                                               i.span,
725                                                               PathKind::Crate,
726                                                               true);
727                         self.ast_map.with_path(i.id, |path| {
728                             cmeta.update_local_path(path)
729                         });
730                         self.sess.cstore.add_extern_mod_stmt_cnum(info.id, cnum);
731                     }
732                     None => ()
733                 }
734             }
735             hir::ItemForeignMod(ref fm) => self.process_foreign_mod(i, fm),
736             _ => { }
737         }
738     }
739
740     fn process_foreign_mod(&mut self, i: &hir::Item, fm: &hir::ForeignMod) {
741         if fm.abi == abi::Rust || fm.abi == abi::RustIntrinsic || fm.abi == abi::PlatformIntrinsic {
742             return;
743         }
744
745         // First, add all of the custom #[link_args] attributes
746         for m in i.attrs.iter().filter(|a| a.check_name("link_args")) {
747             if let Some(linkarg) = m.value_str() {
748                 self.sess.cstore.add_used_link_args(&linkarg);
749             }
750         }
751
752         // Next, process all of the #[link(..)]-style arguments
753         for m in i.attrs.iter().filter(|a| a.check_name("link")) {
754             let items = match m.meta_item_list() {
755                 Some(item) => item,
756                 None => continue,
757             };
758             let kind = items.iter().find(|k| {
759                 k.check_name("kind")
760             }).and_then(|a| a.value_str());
761             let kind = match kind.as_ref().map(|s| &s[..]) {
762                 Some("static") => cstore::NativeStatic,
763                 Some("dylib") => cstore::NativeUnknown,
764                 Some("framework") => cstore::NativeFramework,
765                 Some(k) => {
766                     span_err!(self.sess, m.span, E0458,
767                               "unknown kind: `{}`", k);
768                     cstore::NativeUnknown
769                 }
770                 None => cstore::NativeUnknown
771             };
772             let n = items.iter().find(|n| {
773                 n.check_name("name")
774             }).and_then(|a| a.value_str());
775             let n = match n {
776                 Some(n) => n,
777                 None => {
778                     span_err!(self.sess, m.span, E0459,
779                               "#[link(...)] specified without `name = \"foo\"`");
780                     InternedString::new("foo")
781                 }
782             };
783             register_native_lib(self.sess, Some(m.span), n.to_string(), kind);
784         }
785
786         // Finally, process the #[linked_from = "..."] attribute
787         for m in i.attrs.iter().filter(|a| a.check_name("linked_from")) {
788             let lib_name = match m.value_str() {
789                 Some(name) => name,
790                 None => continue,
791             };
792             let list = self.creader.foreign_item_map.entry(lib_name.to_string())
793                                                     .or_insert(Vec::new());
794             list.extend(fm.items.iter().map(|it| it.id));
795         }
796     }
797 }
798
799 /// Imports the codemap from an external crate into the codemap of the crate
800 /// currently being compiled (the "local crate").
801 ///
802 /// The import algorithm works analogous to how AST items are inlined from an
803 /// external crate's metadata:
804 /// For every FileMap in the external codemap an 'inline' copy is created in the
805 /// local codemap. The correspondence relation between external and local
806 /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
807 /// function. When an item from an external crate is later inlined into this
808 /// crate, this correspondence information is used to translate the span
809 /// information of the inlined item so that it refers the correct positions in
810 /// the local codemap (see `astencode::DecodeContext::tr_span()`).
811 ///
812 /// The import algorithm in the function below will reuse FileMaps already
813 /// existing in the local codemap. For example, even if the FileMap of some
814 /// source file of libstd gets imported many times, there will only ever be
815 /// one FileMap object for the corresponding file in the local codemap.
816 ///
817 /// Note that imported FileMaps do not actually contain the source code of the
818 /// file they represent, just information about length, line breaks, and
819 /// multibyte characters. This information is enough to generate valid debuginfo
820 /// for items inlined from other crates.
821 pub fn import_codemap(local_codemap: &codemap::CodeMap,
822                       metadata: &MetadataBlob)
823                       -> Vec<cstore::ImportedFileMap> {
824     let external_codemap = decoder::get_imported_filemaps(metadata.as_slice());
825
826     let imported_filemaps = external_codemap.into_iter().map(|filemap_to_import| {
827         // Try to find an existing FileMap that can be reused for the filemap to
828         // be imported. A FileMap is reusable if it is exactly the same, just
829         // positioned at a different offset within the codemap.
830         let reusable_filemap = {
831             local_codemap.files
832                          .borrow()
833                          .iter()
834                          .find(|fm| are_equal_modulo_startpos(&fm, &filemap_to_import))
835                          .map(|rc| rc.clone())
836         };
837
838         match reusable_filemap {
839             Some(fm) => {
840                 cstore::ImportedFileMap {
841                     original_start_pos: filemap_to_import.start_pos,
842                     original_end_pos: filemap_to_import.end_pos,
843                     translated_filemap: fm
844                 }
845             }
846             None => {
847                 // We can't reuse an existing FileMap, so allocate a new one
848                 // containing the information we need.
849                 let codemap::FileMap {
850                     name,
851                     start_pos,
852                     end_pos,
853                     lines,
854                     multibyte_chars,
855                     ..
856                 } = filemap_to_import;
857
858                 let source_length = (end_pos - start_pos).to_usize();
859
860                 // Translate line-start positions and multibyte character
861                 // position into frame of reference local to file.
862                 // `CodeMap::new_imported_filemap()` will then translate those
863                 // coordinates to their new global frame of reference when the
864                 // offset of the FileMap is known.
865                 let mut lines = lines.into_inner();
866                 for pos in &mut lines {
867                     *pos = *pos - start_pos;
868                 }
869                 let mut multibyte_chars = multibyte_chars.into_inner();
870                 for mbc in &mut multibyte_chars {
871                     mbc.pos = mbc.pos - start_pos;
872                 }
873
874                 let local_version = local_codemap.new_imported_filemap(name,
875                                                                        source_length,
876                                                                        lines,
877                                                                        multibyte_chars);
878                 cstore::ImportedFileMap {
879                     original_start_pos: start_pos,
880                     original_end_pos: end_pos,
881                     translated_filemap: local_version
882                 }
883             }
884         }
885     }).collect();
886
887     return imported_filemaps;
888
889     fn are_equal_modulo_startpos(fm1: &codemap::FileMap,
890                                  fm2: &codemap::FileMap)
891                                  -> bool {
892         if fm1.name != fm2.name {
893             return false;
894         }
895
896         let lines1 = fm1.lines.borrow();
897         let lines2 = fm2.lines.borrow();
898
899         if lines1.len() != lines2.len() {
900             return false;
901         }
902
903         for (&line1, &line2) in lines1.iter().zip(lines2.iter()) {
904             if (line1 - fm1.start_pos) != (line2 - fm2.start_pos) {
905                 return false;
906             }
907         }
908
909         let multibytes1 = fm1.multibyte_chars.borrow();
910         let multibytes2 = fm2.multibyte_chars.borrow();
911
912         if multibytes1.len() != multibytes2.len() {
913             return false;
914         }
915
916         for (mb1, mb2) in multibytes1.iter().zip(multibytes2.iter()) {
917             if (mb1.bytes != mb2.bytes) ||
918                ((mb1.pos - fm1.start_pos) != (mb2.pos - fm2.start_pos)) {
919                 return false;
920             }
921         }
922
923         true
924     }
925 }