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