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.
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.
11 #![allow(non_camel_case_types)]
13 //! Validates all used crates and extern libraries and loads their metadata
15 use common::rustc_version;
16 use cstore::{self, CStore, CrateSource, MetadataBlob};
18 use loader::{self, CratePaths};
20 use rustc::back::svh::Svh;
21 use rustc::dep_graph::DepNode;
22 use rustc::session::{config, Session};
23 use rustc::session::search_paths::PathKind;
24 use rustc::middle::cstore::{CrateStore, validate_crate_name, ExternCrate};
25 use rustc::util::nodemap::FnvHashMap;
26 use rustc::front::map as hir_map;
28 use std::cell::{RefCell, Cell};
29 use std::path::PathBuf;
35 use syntax::codemap::{self, Span, mk_sp, Pos};
38 use syntax::attr::AttrMetaMethods;
39 use syntax::errors::FatalError;
40 use syntax::parse::token::InternedString;
41 use rustc_front::intravisit::Visitor;
45 pub struct LocalCrateReader<'a, 'b:'a> {
48 creader: CrateReader<'a>,
49 ast_map: &'a hir_map::Map<'b>,
52 pub struct CrateReader<'a> {
55 next_crate_num: ast::CrateNum,
56 foreign_item_map: FnvHashMap<String, Vec<ast::NodeId>>,
57 local_crate_name: String,
60 impl<'a, 'b, 'hir> Visitor<'hir> for LocalCrateReader<'a, 'b> {
61 fn visit_item(&mut self, a: &'hir hir::Item) {
66 fn dump_crates(cstore: &CStore) {
67 info!("resolved crates:");
68 cstore.iter_crate_data_origins(|_, data, opt_source| {
69 info!(" name: {}", data.name());
70 info!(" cnum: {}", data.cnum);
71 info!(" hash: {}", data.hash());
72 info!(" reqd: {}", data.explicitly_linked.get());
74 let CrateSource { dylib, rlib, cnum: _ } = cs;
75 dylib.map(|dl| info!(" dylib: {}", dl.0.display()));
76 rlib.map(|rl| info!(" rlib: {}", rl.0.display()));
81 fn should_link(i: &ast::Item) -> bool {
82 !attr::contains_name(&i.attrs, "no_link")
85 fn should_link_hir(i: &hir::Item) -> bool {
86 !attr::contains_name(&i.attrs, "no_link")
96 fn register_native_lib(sess: &Session,
100 kind: cstore::NativeLibraryKind) {
104 span_err!(sess, span, E0454,
105 "#[link(name = \"\")] given with empty name");
108 sess.err("empty library name given via `-l`");
113 let is_osx = sess.target.target.options.is_like_osx;
114 if kind == cstore::NativeFramework && !is_osx {
115 let msg = "native frameworks are only available on OSX targets";
118 span_err!(sess, span, E0455,
121 None => sess.err(msg),
124 cstore.add_used_library(name, kind);
127 // Extra info about a crate loaded for plugins or exported macros.
128 struct ExtensionCrate {
130 dylib: Option<PathBuf>,
135 Registered(Rc<cstore::crate_metadata>),
140 pub fn as_slice<'a>(&'a self) -> &'a [u8] {
142 PMDSource::Registered(ref cmd) => cmd.data(),
143 PMDSource::Owned(ref mdb) => mdb.as_slice(),
148 impl<'a> CrateReader<'a> {
149 pub fn new(sess: &'a Session,
151 local_crate_name: &str) -> CrateReader<'a> {
155 next_crate_num: cstore.next_crate_num(),
156 foreign_item_map: FnvHashMap(),
157 local_crate_name: local_crate_name.to_owned(),
161 fn extract_crate_info(&self, i: &ast::Item) -> Option<CrateInfo> {
163 ast::ItemKind::ExternCrate(ref path_opt) => {
164 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
166 let name = match *path_opt {
168 validate_crate_name(Some(self.sess), &name.as_str(),
172 None => i.ident.to_string(),
175 ident: i.ident.to_string(),
178 should_link: should_link(i),
185 // Dup of the above, but for the hir
186 fn extract_crate_info_hir(&self, i: &hir::Item) -> Option<CrateInfo> {
188 hir::ItemExternCrate(ref path_opt) => {
189 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
191 let name = match *path_opt {
193 validate_crate_name(Some(self.sess), &name.as_str(),
197 None => i.name.to_string(),
200 ident: i.name.to_string(),
203 should_link: should_link_hir(i),
210 fn existing_match(&self, name: &str, hash: Option<&Svh>, kind: PathKind)
211 -> Option<ast::CrateNum> {
213 self.cstore.iter_crate_data(|cnum, data| {
214 if data.name != name { return }
217 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
222 // When the hash is None we're dealing with a top-level dependency
223 // in which case we may have a specification on the command line for
224 // this library. Even though an upstream library may have loaded
225 // something of the same name, we have to make sure it was loaded
226 // from the exact same location as well.
228 // We're also sure to compare *paths*, not actual byte slices. The
229 // `source` stores paths which are normalized which may be different
230 // from the strings on the command line.
231 let source = self.cstore.used_crate_source(cnum);
232 if let Some(locs) = self.sess.opts.externs.get(name) {
233 let found = locs.iter().any(|l| {
234 let l = fs::canonicalize(l).ok();
235 source.dylib.as_ref().map(|p| &p.0) == l.as_ref() ||
236 source.rlib.as_ref().map(|p| &p.0) == l.as_ref()
244 // Alright, so we've gotten this far which means that `data` has the
245 // right name, we don't have a hash, and we don't have a --extern
246 // pointing for ourselves. We're still not quite yet done because we
247 // have to make sure that this crate was found in the crate lookup
248 // path (this is a top-level dependency) as we don't want to
249 // implicitly load anything inside the dependency lookup path.
250 let prev_kind = source.dylib.as_ref().or(source.rlib.as_ref())
252 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
259 fn verify_rustc_version(&self,
262 metadata: &MetadataBlob) {
263 let crate_rustc_version = decoder::crate_rustc_version(metadata.as_slice());
264 if crate_rustc_version != Some(rustc_version()) {
265 let mut err = struct_span_fatal!(self.sess, span, E0514,
266 "the crate `{}` has been compiled with {}, which is \
267 incompatible with this version of rustc",
270 .as_ref().map(|s| &**s)
271 .unwrap_or("an old version of rustc"));
272 err.fileline_help(span, "consider removing the compiled binaries and recompiling \
273 with your current version of rustc");
278 fn verify_no_symbol_conflicts(&self,
280 metadata: &MetadataBlob) {
281 let disambiguator = decoder::get_crate_disambiguator(metadata.as_slice());
282 let crate_name = decoder::get_crate_name(metadata.as_slice());
284 // Check for (potential) conflicts with the local crate
285 if self.local_crate_name == crate_name &&
286 self.sess.crate_disambiguator.get().as_str() == disambiguator {
287 span_fatal!(self.sess, span, E0519,
288 "the current crate is indistinguishable from one of its \
289 dependencies: it has the same crate-name `{}` and was \
290 compiled with the same `-C metadata` arguments. This \
291 will result in symbol conflicts between the two.",
295 let svh = decoder::get_crate_hash(metadata.as_slice());
296 // Check for conflicts with any crate loaded so far
297 self.cstore.iter_crate_data(|_, other| {
298 if other.name() == crate_name && // same crate-name
299 other.disambiguator() == disambiguator && // same crate-disambiguator
300 other.hash() != svh { // but different SVH
301 span_fatal!(self.sess, span, E0521,
302 "found two different crates with name `{}` that are \
303 not distinguished by differing `-C metadata`. This \
304 will result in symbol conflicts between the two.",
310 fn register_crate(&mut self,
311 root: &Option<CratePaths>,
315 lib: loader::Library,
316 explicitly_linked: bool)
317 -> (ast::CrateNum, Rc<cstore::crate_metadata>,
318 cstore::CrateSource) {
319 self.verify_rustc_version(name, span, &lib.metadata);
320 self.verify_no_symbol_conflicts(span, &lib.metadata);
322 // Claim this crate number and cache it
323 let cnum = self.next_crate_num;
324 self.next_crate_num += 1;
326 // Stash paths for top-most crate locally if necessary.
327 let crate_paths = if root.is_none() {
329 ident: ident.to_string(),
330 dylib: lib.dylib.clone().map(|p| p.0),
331 rlib: lib.rlib.clone().map(|p| p.0),
336 // Maintain a reference to the top most crate.
337 let root = if root.is_some() { root } else { &crate_paths };
339 let loader::Library { dylib, rlib, metadata } = lib;
341 let cnum_map = self.resolve_crate_deps(root, metadata.as_slice(), span);
342 let staged_api = self.is_staged_api(metadata.as_slice());
344 let cmeta = Rc::new(cstore::crate_metadata {
345 name: name.to_string(),
346 extern_crate: Cell::new(None),
347 index: decoder::load_index(metadata.as_slice()),
348 xref_index: decoder::load_xrefs(metadata.as_slice()),
350 cnum_map: RefCell::new(cnum_map),
352 codemap_import_info: RefCell::new(vec![]),
353 staged_api: staged_api,
354 explicitly_linked: Cell::new(explicitly_linked),
357 let source = cstore::CrateSource {
363 self.cstore.set_crate_data(cnum, cmeta.clone());
364 self.cstore.add_used_crate_source(source.clone());
365 (cnum, cmeta, source)
368 fn is_staged_api(&self, data: &[u8]) -> bool {
369 let attrs = decoder::get_crate_attributes(data);
371 if attr.name() == "stable" || attr.name() == "unstable" {
378 fn resolve_crate(&mut self,
379 root: &Option<CratePaths>,
385 explicitly_linked: bool)
386 -> (ast::CrateNum, Rc<cstore::crate_metadata>, cstore::CrateSource) {
388 Previous(ast::CrateNum),
389 Loaded(loader::Library),
391 let result = match self.existing_match(name, hash, kind) {
392 Some(cnum) => LookupResult::Previous(cnum),
394 let mut load_ctxt = loader::Context {
399 hash: hash.map(|a| &*a),
400 filesearch: self.sess.target_filesearch(kind),
401 target: &self.sess.target.target,
402 triple: &self.sess.opts.target_triple,
404 rejected_via_hash: vec!(),
405 rejected_via_triple: vec!(),
406 rejected_via_kind: vec!(),
407 should_match_name: true,
409 let library = load_ctxt.load_library_crate();
411 // In the case that we're loading a crate, but not matching
412 // against a hash, we could load a crate which has the same hash
413 // as an already loaded crate. If this is the case prevent
414 // duplicates by just using the first crate.
415 let meta_hash = decoder::get_crate_hash(library.metadata
417 let mut result = LookupResult::Loaded(library);
418 self.cstore.iter_crate_data(|cnum, data| {
419 if data.name() == name && meta_hash == data.hash() {
420 assert!(hash.is_none());
421 result = LookupResult::Previous(cnum);
429 LookupResult::Previous(cnum) => {
430 let data = self.cstore.get_crate_data(cnum);
431 if explicitly_linked && !data.explicitly_linked.get() {
432 data.explicitly_linked.set(explicitly_linked);
434 (cnum, data, self.cstore.used_crate_source(cnum))
436 LookupResult::Loaded(library) => {
437 self.register_crate(root, ident, name, span, library,
443 fn update_extern_crate(&mut self,
445 mut extern_crate: ExternCrate)
447 let cmeta = self.cstore.get_crate_data(cnum);
448 let old_extern_crate = cmeta.extern_crate.get();
451 // - something over nothing (tuple.0);
452 // - direct extern crate to indirect (tuple.1);
453 // - shorter paths to longer (tuple.2).
454 let new_rank = (true, extern_crate.direct, !extern_crate.path_len);
455 let old_rank = match old_extern_crate {
456 None => (false, false, !0),
457 Some(ref c) => (true, c.direct, !c.path_len),
460 if old_rank >= new_rank {
461 return; // no change needed
464 cmeta.extern_crate.set(Some(extern_crate));
466 // Propagate the extern crate info to dependencies.
467 extern_crate.direct = false;
468 for &dep_cnum in cmeta.cnum_map.borrow().values() {
469 self.update_extern_crate(dep_cnum, extern_crate);
473 // Go through the crate metadata and load any crates that it references
474 fn resolve_crate_deps(&mut self,
475 root: &Option<CratePaths>,
478 -> cstore::cnum_map {
479 debug!("resolving deps of external crate");
480 // The map from crate numbers in the crate we're resolving to local crate
482 decoder::get_crate_deps(cdata).iter().map(|dep| {
483 debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
484 let (local_cnum, _, _) = self.resolve_crate(root,
489 PathKind::Dependency,
490 dep.explicitly_linked);
491 (dep.cnum, local_cnum)
495 fn read_extension_crate(&mut self, span: Span, info: &CrateInfo) -> ExtensionCrate {
496 let target_triple = &self.sess.opts.target_triple[..];
497 let is_cross = target_triple != config::host_triple();
498 let mut should_link = info.should_link && !is_cross;
499 let mut target_only = false;
500 let ident = info.ident.clone();
501 let name = info.name.clone();
502 let mut load_ctxt = loader::Context {
506 crate_name: &name[..],
508 filesearch: self.sess.host_filesearch(PathKind::Crate),
509 target: &self.sess.host,
510 triple: config::host_triple(),
512 rejected_via_hash: vec!(),
513 rejected_via_triple: vec!(),
514 rejected_via_kind: vec!(),
515 should_match_name: true,
517 let library = match load_ctxt.maybe_load_library_crate() {
519 None if is_cross => {
520 // Try loading from target crates. This will abort later if we
521 // try to load a plugin registrar function,
523 should_link = info.should_link;
525 load_ctxt.target = &self.sess.target.target;
526 load_ctxt.triple = target_triple;
527 load_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
528 load_ctxt.load_library_crate()
530 None => { load_ctxt.report_load_errs(); unreachable!() },
533 let dylib = library.dylib.clone();
534 let register = should_link && self.existing_match(&info.name,
536 PathKind::Crate).is_none();
537 let metadata = if register {
538 // Register crate now to avoid double-reading metadata
539 let (_, cmd, _) = self.register_crate(&None, &info.ident,
540 &info.name, span, library,
542 PMDSource::Registered(cmd)
544 // Not registering the crate; just hold on to the metadata
545 PMDSource::Owned(library.metadata)
550 dylib: dylib.map(|p| p.0),
551 target_only: target_only,
555 /// Read exported macros.
556 pub fn read_exported_macros(&mut self, item: &ast::Item) -> Vec<ast::MacroDef> {
557 let ci = self.extract_crate_info(item).unwrap();
558 let ekrate = self.read_extension_crate(item.span, &ci);
560 let source_name = format!("<{} macros>", item.ident);
561 let mut macros = vec![];
562 decoder::each_exported_macro(ekrate.metadata.as_slice(),
564 |name, attrs, span, body| {
565 // NB: Don't use parse::parse_tts_from_source_str because it parses with
567 let mut p = parse::new_parser_from_source_str(&self.sess.parse_sess,
568 self.sess.opts.cfg.clone(),
572 let body = match p.parse_all_token_trees() {
579 let local_span = mk_sp(lo, p.last_span.hi);
581 // Mark the attrs as used
583 attr::mark_used(attr);
586 macros.push(ast::MacroDef {
587 ident: ast::Ident::with_empty_ctxt(name),
589 id: ast::DUMMY_NODE_ID,
591 imported_from: Some(item.ident),
592 // overridden in plugin/load.rs
595 allow_internal_unstable: false,
599 self.sess.imported_macro_spans.borrow_mut()
600 .insert(local_span, (name.as_str().to_string(), span));
607 /// Look for a plugin registrar. Returns library path and symbol name.
608 pub fn find_plugin_registrar(&mut self, span: Span, name: &str)
609 -> Option<(PathBuf, String)> {
610 let ekrate = self.read_extension_crate(span, &CrateInfo {
611 name: name.to_string(),
612 ident: name.to_string(),
613 id: ast::DUMMY_NODE_ID,
617 if ekrate.target_only {
618 // Need to abort before syntax expansion.
619 let message = format!("plugin `{}` is not available for triple `{}` \
622 config::host_triple(),
623 self.sess.opts.target_triple);
624 span_fatal!(self.sess, span, E0456, "{}", &message[..]);
628 decoder::get_plugin_registrar_fn(ekrate.metadata.as_slice())
629 .map(|id| decoder::get_symbol_from_buf(ekrate.metadata.as_slice(), id));
631 match (ekrate.dylib.as_ref(), registrar) {
632 (Some(dylib), Some(reg)) => Some((dylib.to_path_buf(), reg)),
634 span_err!(self.sess, span, E0457,
635 "plugin `{}` only found in rlib format, but must be available \
638 // No need to abort because the loading code will just ignore this
646 fn register_statically_included_foreign_items(&mut self) {
647 let libs = self.cstore.get_used_libraries();
648 for (lib, list) in self.foreign_item_map.iter() {
649 let is_static = libs.borrow().iter().any(|&(ref name, kind)| {
650 lib == name && kind == cstore::NativeStatic
654 self.cstore.add_statically_included_foreign_item(*id);
660 fn inject_allocator_crate(&mut self) {
661 // Make sure that we actually need an allocator, if none of our
662 // dependencies need one then we definitely don't!
664 // Also, if one of our dependencies has an explicit allocator, then we
665 // also bail out as we don't need to implicitly inject one.
666 let mut needs_allocator = false;
667 let mut found_required_allocator = false;
668 self.cstore.iter_crate_data(|cnum, data| {
669 needs_allocator = needs_allocator || data.needs_allocator();
670 if data.is_allocator() {
671 debug!("{} required by rlib and is an allocator", data.name());
672 self.inject_allocator_dependency(cnum);
673 found_required_allocator = found_required_allocator ||
674 data.explicitly_linked.get();
677 if !needs_allocator || found_required_allocator { return }
679 // At this point we've determined that we need an allocator and no
680 // previous allocator has been activated. We look through our outputs of
681 // crate types to see what kind of allocator types we may need.
683 // The main special output type here is that rlibs do **not** need an
684 // allocator linked in (they're just object files), only final products
685 // (exes, dylibs, staticlibs) need allocators.
686 let mut need_lib_alloc = false;
687 let mut need_exe_alloc = false;
688 for ct in self.sess.crate_types.borrow().iter() {
690 config::CrateTypeExecutable => need_exe_alloc = true,
691 config::CrateTypeDylib |
692 config::CrateTypeStaticlib => need_lib_alloc = true,
693 config::CrateTypeRlib => {}
696 if !need_lib_alloc && !need_exe_alloc { return }
698 // The default allocator crate comes from the custom target spec, and we
699 // choose between the standard library allocator or exe allocator. This
700 // distinction exists because the default allocator for binaries (where
701 // the world is Rust) is different than library (where the world is
702 // likely *not* Rust).
704 // If a library is being produced, but we're also flagged with `-C
705 // prefer-dynamic`, then we interpret this as a *Rust* dynamic library
706 // is being produced so we use the exe allocator instead.
708 // What this boils down to is:
710 // * Binaries use jemalloc
711 // * Staticlibs and Rust dylibs use system malloc
712 // * Rust dylibs used as dependencies to rust use jemalloc
713 let name = if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
714 &self.sess.target.target.options.lib_allocation_crate
716 &self.sess.target.target.options.exe_allocation_crate
718 let (cnum, data, _) = self.resolve_crate(&None, name, name, None,
720 PathKind::Crate, false);
722 // To ensure that the `-Z allocation-crate=foo` option isn't abused, and
723 // to ensure that the allocator is indeed an allocator, we verify that
724 // the crate loaded here is indeed tagged #![allocator].
725 if !data.is_allocator() {
726 self.sess.err(&format!("the allocator crate `{}` is not tagged \
727 with #![allocator]", data.name()));
730 self.sess.injected_allocator.set(Some(cnum));
731 self.inject_allocator_dependency(cnum);
734 fn inject_allocator_dependency(&self, allocator: ast::CrateNum) {
735 // Before we inject any dependencies, make sure we don't inject a
736 // circular dependency by validating that this allocator crate doesn't
737 // transitively depend on any `#![needs_allocator]` crates.
738 validate(self, allocator, allocator);
740 // All crates tagged with `needs_allocator` do not explicitly depend on
741 // the allocator selected for this compile, but in order for this
742 // compilation to be successfully linked we need to inject a dependency
743 // (to order the crates on the command line correctly).
745 // Here we inject a dependency from all crates with #![needs_allocator]
746 // to the crate tagged with #![allocator] for this compilation unit.
747 self.cstore.iter_crate_data(|cnum, data| {
748 if !data.needs_allocator() {
752 info!("injecting a dep from {} to {}", cnum, allocator);
753 let mut cnum_map = data.cnum_map.borrow_mut();
754 let remote_cnum = cnum_map.len() + 1;
755 let prev = cnum_map.insert(remote_cnum as ast::CrateNum, allocator);
756 assert!(prev.is_none());
759 fn validate(me: &CrateReader, krate: ast::CrateNum,
760 allocator: ast::CrateNum) {
761 let data = me.cstore.get_crate_data(krate);
762 if data.needs_allocator() {
763 let krate_name = data.name();
764 let data = me.cstore.get_crate_data(allocator);
765 let alloc_name = data.name();
766 me.sess.err(&format!("the allocator crate `{}` cannot depend \
767 on a crate that needs an allocator, but \
768 it depends on `{}`", alloc_name,
772 for (_, &dep) in data.cnum_map.borrow().iter() {
773 validate(me, dep, allocator);
779 impl<'a, 'b> LocalCrateReader<'a, 'b> {
780 pub fn new(sess: &'a Session,
782 map: &'a hir_map::Map<'b>,
783 local_crate_name: &str)
784 -> LocalCrateReader<'a, 'b> {
788 creader: CrateReader::new(sess, cstore, local_crate_name),
793 // Traverses an AST, reading all the information about use'd crates and
794 // extern libraries necessary for later resolving, typechecking, linking,
796 pub fn read_crates(&mut self) {
797 let _task = self.ast_map.dep_graph.in_task(DepNode::CrateReader);
798 let krate = self.ast_map.krate();
800 self.process_crate(krate);
801 krate.visit_all_items(self);
802 self.creader.inject_allocator_crate();
804 if log_enabled!(log::INFO) {
805 dump_crates(&self.cstore);
808 for &(ref name, kind) in &self.sess.opts.libs {
809 register_native_lib(self.sess, self.cstore, None, name.clone(), kind);
811 self.creader.register_statically_included_foreign_items();
814 fn process_crate(&self, c: &hir::Crate) {
815 for a in c.attrs.iter().filter(|m| m.name() == "link_args") {
816 match a.value_str() {
817 Some(ref linkarg) => self.cstore.add_used_link_args(&linkarg),
818 None => { /* fallthrough */ }
823 fn process_item(&mut self, i: &hir::Item) {
825 hir::ItemExternCrate(_) => {
826 if !should_link_hir(i) {
830 match self.creader.extract_crate_info_hir(i) {
832 let (cnum, _, _) = self.creader.resolve_crate(&None,
839 let def_id = self.ast_map.local_def_id(i.id);
841 let len = self.ast_map.def_path(def_id).data.len();
843 self.creader.update_extern_crate(cnum,
850 self.cstore.add_extern_mod_stmt_cnum(info.id, cnum);
855 hir::ItemForeignMod(ref fm) => self.process_foreign_mod(i, fm),
860 fn process_foreign_mod(&mut self, i: &hir::Item, fm: &hir::ForeignMod) {
861 if fm.abi == Abi::Rust || fm.abi == Abi::RustIntrinsic || fm.abi == Abi::PlatformIntrinsic {
865 // First, add all of the custom #[link_args] attributes
866 for m in i.attrs.iter().filter(|a| a.check_name("link_args")) {
867 if let Some(linkarg) = m.value_str() {
868 self.cstore.add_used_link_args(&linkarg);
872 // Next, process all of the #[link(..)]-style arguments
873 for m in i.attrs.iter().filter(|a| a.check_name("link")) {
874 let items = match m.meta_item_list() {
878 let kind = items.iter().find(|k| {
880 }).and_then(|a| a.value_str());
881 let kind = match kind.as_ref().map(|s| &s[..]) {
882 Some("static") => cstore::NativeStatic,
883 Some("dylib") => cstore::NativeUnknown,
884 Some("framework") => cstore::NativeFramework,
886 span_err!(self.sess, m.span, E0458,
887 "unknown kind: `{}`", k);
888 cstore::NativeUnknown
890 None => cstore::NativeUnknown
892 let n = items.iter().find(|n| {
894 }).and_then(|a| a.value_str());
898 span_err!(self.sess, m.span, E0459,
899 "#[link(...)] specified without `name = \"foo\"`");
900 InternedString::new("foo")
903 register_native_lib(self.sess, self.cstore, Some(m.span), n.to_string(), kind);
906 // Finally, process the #[linked_from = "..."] attribute
907 for m in i.attrs.iter().filter(|a| a.check_name("linked_from")) {
908 let lib_name = match m.value_str() {
912 let list = self.creader.foreign_item_map.entry(lib_name.to_string())
913 .or_insert(Vec::new());
914 list.extend(fm.items.iter().map(|it| it.id));
919 /// Imports the codemap from an external crate into the codemap of the crate
920 /// currently being compiled (the "local crate").
922 /// The import algorithm works analogous to how AST items are inlined from an
923 /// external crate's metadata:
924 /// For every FileMap in the external codemap an 'inline' copy is created in the
925 /// local codemap. The correspondence relation between external and local
926 /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
927 /// function. When an item from an external crate is later inlined into this
928 /// crate, this correspondence information is used to translate the span
929 /// information of the inlined item so that it refers the correct positions in
930 /// the local codemap (see `astencode::DecodeContext::tr_span()`).
932 /// The import algorithm in the function below will reuse FileMaps already
933 /// existing in the local codemap. For example, even if the FileMap of some
934 /// source file of libstd gets imported many times, there will only ever be
935 /// one FileMap object for the corresponding file in the local codemap.
937 /// Note that imported FileMaps do not actually contain the source code of the
938 /// file they represent, just information about length, line breaks, and
939 /// multibyte characters. This information is enough to generate valid debuginfo
940 /// for items inlined from other crates.
941 pub fn import_codemap(local_codemap: &codemap::CodeMap,
942 metadata: &MetadataBlob)
943 -> Vec<cstore::ImportedFileMap> {
944 let external_codemap = decoder::get_imported_filemaps(metadata.as_slice());
946 let imported_filemaps = external_codemap.into_iter().map(|filemap_to_import| {
947 // Try to find an existing FileMap that can be reused for the filemap to
948 // be imported. A FileMap is reusable if it is exactly the same, just
949 // positioned at a different offset within the codemap.
950 let reusable_filemap = {
954 .find(|fm| are_equal_modulo_startpos(&fm, &filemap_to_import))
955 .map(|rc| rc.clone())
958 match reusable_filemap {
960 cstore::ImportedFileMap {
961 original_start_pos: filemap_to_import.start_pos,
962 original_end_pos: filemap_to_import.end_pos,
963 translated_filemap: fm
967 // We can't reuse an existing FileMap, so allocate a new one
968 // containing the information we need.
969 let codemap::FileMap {
976 } = filemap_to_import;
978 let source_length = (end_pos - start_pos).to_usize();
980 // Translate line-start positions and multibyte character
981 // position into frame of reference local to file.
982 // `CodeMap::new_imported_filemap()` will then translate those
983 // coordinates to their new global frame of reference when the
984 // offset of the FileMap is known.
985 let mut lines = lines.into_inner();
986 for pos in &mut lines {
987 *pos = *pos - start_pos;
989 let mut multibyte_chars = multibyte_chars.into_inner();
990 for mbc in &mut multibyte_chars {
991 mbc.pos = mbc.pos - start_pos;
994 let local_version = local_codemap.new_imported_filemap(name,
998 cstore::ImportedFileMap {
999 original_start_pos: start_pos,
1000 original_end_pos: end_pos,
1001 translated_filemap: local_version
1007 return imported_filemaps;
1009 fn are_equal_modulo_startpos(fm1: &codemap::FileMap,
1010 fm2: &codemap::FileMap)
1012 if fm1.name != fm2.name {
1016 let lines1 = fm1.lines.borrow();
1017 let lines2 = fm2.lines.borrow();
1019 if lines1.len() != lines2.len() {
1023 for (&line1, &line2) in lines1.iter().zip(lines2.iter()) {
1024 if (line1 - fm1.start_pos) != (line2 - fm2.start_pos) {
1029 let multibytes1 = fm1.multibyte_chars.borrow();
1030 let multibytes2 = fm2.multibyte_chars.borrow();
1032 if multibytes1.len() != multibytes2.len() {
1036 for (mb1, mb2) in multibytes1.iter().zip(multibytes2.iter()) {
1037 if (mb1.bytes != mb2.bytes) ||
1038 ((mb1.pos - fm1.start_pos) != (mb2.pos - fm2.start_pos)) {