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
16 use session::{config, Session};
17 use session::search_paths::PathKind;
18 use metadata::common::rustc_version;
20 use metadata::cstore::{CStore, CrateSource, MetadataBlob};
21 use metadata::decoder;
23 use metadata::loader::CratePaths;
24 use util::nodemap::FnvHashMap;
25 use front::map as hir_map;
27 use std::cell::{RefCell, Cell};
28 use std::path::PathBuf;
34 use syntax::codemap::{self, Span, mk_sp, Pos};
37 use syntax::attr::AttrMetaMethods;
38 use syntax::parse::token::InternedString;
39 use syntax::util::small_vector::SmallVector;
40 use rustc_front::intravisit::Visitor;
44 pub struct LocalCrateReader<'a, 'b:'a> {
46 creader: CrateReader<'a>,
47 ast_map: &'a hir_map::Map<'b>,
50 pub struct CrateReader<'a> {
52 next_crate_num: ast::CrateNum,
53 foreign_item_map: FnvHashMap<String, Vec<ast::NodeId>>,
56 impl<'a, 'b, 'hir> Visitor<'hir> for LocalCrateReader<'a, 'b> {
57 fn visit_item(&mut self, a: &'hir hir::Item) {
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());
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()));
77 fn should_link(i: &ast::Item) -> bool {
78 !attr::contains_name(&i.attrs, "no_link")
81 fn should_link_hir(i: &hir::Item) -> bool {
82 !attr::contains_name(&i.attrs, "no_link")
92 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
95 (_, None) => panic!("{}", s),
96 (Some(sp), Some(sess)) => sess.span_err(sp, s),
97 (None, Some(sess)) => sess.err(s),
101 say("crate name must not be empty");
104 if c.is_alphanumeric() { continue }
105 if c == '_' { continue }
106 say(&format!("invalid character `{}` in crate name: `{}`", c, s));
109 Some(sess) => sess.abort_if_errors(),
115 fn register_native_lib(sess: &Session,
118 kind: cstore::NativeLibraryKind) {
122 span_err!(sess, span, E0454,
123 "#[link(name = \"\")] given with empty name");
126 sess.err("empty library name given via `-l`");
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";
136 span_err!(sess, span, E0455,
139 None => sess.err(msg),
142 sess.cstore.add_used_library(name, kind);
145 // Extra info about a crate loaded for plugins or exported macros.
146 struct ExtensionCrate {
148 dylib: Option<PathBuf>,
153 Registered(Rc<cstore::crate_metadata>),
158 pub fn as_slice<'a>(&'a self) -> &'a [u8] {
160 PMDSource::Registered(ref cmd) => cmd.data(),
161 PMDSource::Owned(ref mdb) => mdb.as_slice(),
166 impl<'a> CrateReader<'a> {
167 pub fn new(sess: &'a Session) -> CrateReader<'a> {
170 next_crate_num: sess.cstore.next_crate_num(),
171 foreign_item_map: FnvHashMap(),
175 fn extract_crate_info(&self, i: &ast::Item) -> Option<CrateInfo> {
177 ast::ItemExternCrate(ref path_opt) => {
178 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
180 let name = match *path_opt {
182 validate_crate_name(Some(self.sess), &name.as_str(),
186 None => i.ident.to_string(),
189 ident: i.ident.to_string(),
192 should_link: should_link(i),
199 // Dup of the above, but for the hir
200 fn extract_crate_info_hir(&self, i: &hir::Item) -> Option<CrateInfo> {
202 hir::ItemExternCrate(ref path_opt) => {
203 debug!("resolving extern crate stmt. ident: {} path_opt: {:?}",
205 let name = match *path_opt {
207 validate_crate_name(Some(self.sess), &name.as_str(),
211 None => i.name.to_string(),
214 ident: i.name.to_string(),
217 should_link: should_link_hir(i),
224 fn existing_match(&self, name: &str, hash: Option<&Svh>, kind: PathKind)
225 -> Option<ast::CrateNum> {
227 self.sess.cstore.iter_crate_data(|cnum, data| {
228 if data.name != name { return }
231 Some(hash) if *hash == data.hash() => { ret = Some(cnum); return }
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.
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()
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())
266 if ret.is_none() && (prev_kind == kind || prev_kind == PathKind::All) {
273 fn verify_rustc_version(&self,
276 metadata: &MetadataBlob) {
277 let crate_rustc_version = decoder::crate_rustc_version(metadata.as_slice());
278 if crate_rustc_version != Some(rustc_version()) {
279 span_err!(self.sess, span, E0514,
280 "the crate `{}` has been compiled with {}, which is \
281 incompatible with this version of rustc",
284 .as_ref().map(|s|&**s)
285 .unwrap_or("an old version of rustc")
287 self.sess.abort_if_errors();
291 fn register_crate(&mut self,
292 root: &Option<CratePaths>,
296 lib: loader::Library,
297 explicitly_linked: bool)
298 -> (ast::CrateNum, Rc<cstore::crate_metadata>,
299 cstore::CrateSource) {
300 self.verify_rustc_version(name, span, &lib.metadata);
302 // Claim this crate number and cache it
303 let cnum = self.next_crate_num;
304 self.next_crate_num += 1;
306 // Stash paths for top-most crate locally if necessary.
307 let crate_paths = if root.is_none() {
309 ident: ident.to_string(),
310 dylib: lib.dylib.clone().map(|p| p.0),
311 rlib: lib.rlib.clone().map(|p| p.0),
316 // Maintain a reference to the top most crate.
317 let root = if root.is_some() { root } else { &crate_paths };
319 let loader::Library { dylib, rlib, metadata } = lib;
321 let cnum_map = self.resolve_crate_deps(root, metadata.as_slice(), span);
322 let staged_api = self.is_staged_api(metadata.as_slice());
324 let cmeta = Rc::new(cstore::crate_metadata {
325 name: name.to_string(),
326 local_path: RefCell::new(SmallVector::zero()),
327 local_def_path: RefCell::new(vec![]),
328 index: decoder::load_index(metadata.as_slice()),
329 xref_index: decoder::load_xrefs(metadata.as_slice()),
331 cnum_map: RefCell::new(cnum_map),
333 codemap_import_info: RefCell::new(vec![]),
335 staged_api: staged_api,
336 explicitly_linked: Cell::new(explicitly_linked),
339 let source = cstore::CrateSource {
345 self.sess.cstore.set_crate_data(cnum, cmeta.clone());
346 self.sess.cstore.add_used_crate_source(source.clone());
347 (cnum, cmeta, source)
350 fn is_staged_api(&self, data: &[u8]) -> bool {
351 let attrs = decoder::get_crate_attributes(data);
353 if &attr.name()[..] == "staged_api" {
354 match attr.node.value.node { ast::MetaWord(_) => return true, _ => (/*pass*/) }
361 fn resolve_crate(&mut self,
362 root: &Option<CratePaths>,
368 explicitly_linked: bool)
369 -> (ast::CrateNum, Rc<cstore::crate_metadata>,
370 cstore::CrateSource) {
371 match self.existing_match(name, hash, kind) {
373 let mut load_ctxt = loader::Context {
378 hash: hash.map(|a| &*a),
379 filesearch: self.sess.target_filesearch(kind),
380 target: &self.sess.target.target,
381 triple: &self.sess.opts.target_triple,
383 rejected_via_hash: vec!(),
384 rejected_via_triple: vec!(),
385 rejected_via_kind: vec!(),
386 should_match_name: true,
388 let library = load_ctxt.load_library_crate();
389 self.register_crate(root, ident, name, span, library,
393 let data = self.sess.cstore.get_crate_data(cnum);
394 if explicitly_linked && !data.explicitly_linked.get() {
395 data.explicitly_linked.set(explicitly_linked);
397 (cnum, data, self.sess.cstore.get_used_crate_source(cnum).unwrap())
402 // Go through the crate metadata and load any crates that it references
403 fn resolve_crate_deps(&mut self,
404 root: &Option<CratePaths>,
405 cdata: &[u8], span : Span)
406 -> cstore::cnum_map {
407 debug!("resolving deps of external crate");
408 // The map from crate numbers in the crate we're resolving to local crate
410 decoder::get_crate_deps(cdata).iter().map(|dep| {
411 debug!("resolving dep crate {} hash: `{}`", dep.name, dep.hash);
412 let (local_cnum, _, _) = self.resolve_crate(root,
417 PathKind::Dependency,
418 dep.explicitly_linked);
419 (dep.cnum, local_cnum)
423 fn read_extension_crate(&mut self, span: Span, info: &CrateInfo) -> ExtensionCrate {
424 let target_triple = &self.sess.opts.target_triple[..];
425 let is_cross = target_triple != config::host_triple();
426 let mut should_link = info.should_link && !is_cross;
427 let mut target_only = false;
428 let ident = info.ident.clone();
429 let name = info.name.clone();
430 let mut load_ctxt = loader::Context {
434 crate_name: &name[..],
436 filesearch: self.sess.host_filesearch(PathKind::Crate),
437 target: &self.sess.host,
438 triple: config::host_triple(),
440 rejected_via_hash: vec!(),
441 rejected_via_triple: vec!(),
442 rejected_via_kind: vec!(),
443 should_match_name: true,
445 let library = match load_ctxt.maybe_load_library_crate() {
447 None if is_cross => {
448 // Try loading from target crates. This will abort later if we
449 // try to load a plugin registrar function,
451 should_link = info.should_link;
453 load_ctxt.target = &self.sess.target.target;
454 load_ctxt.triple = target_triple;
455 load_ctxt.filesearch = self.sess.target_filesearch(PathKind::Crate);
456 load_ctxt.load_library_crate()
458 None => { load_ctxt.report_load_errs(); unreachable!() },
461 let dylib = library.dylib.clone();
462 let register = should_link && self.existing_match(&info.name,
464 PathKind::Crate).is_none();
465 let metadata = if register {
466 // Register crate now to avoid double-reading metadata
467 let (_, cmd, _) = self.register_crate(&None, &info.ident,
468 &info.name, span, library,
470 PMDSource::Registered(cmd)
472 // Not registering the crate; just hold on to the metadata
473 PMDSource::Owned(library.metadata)
478 dylib: dylib.map(|p| p.0),
479 target_only: target_only,
483 /// Read exported macros.
484 pub fn read_exported_macros(&mut self, item: &ast::Item) -> Vec<ast::MacroDef> {
485 let ci = self.extract_crate_info(item).unwrap();
486 let ekrate = self.read_extension_crate(item.span, &ci);
488 let source_name = format!("<{} macros>", item.ident);
489 let mut macros = vec![];
490 decoder::each_exported_macro(ekrate.metadata.as_slice(),
491 &*self.sess.cstore.intr,
492 |name, attrs, body| {
493 // NB: Don't use parse::parse_tts_from_source_str because it parses with
495 let mut p = parse::new_parser_from_source_str(&self.sess.parse_sess,
496 self.sess.opts.cfg.clone(),
500 let body = match p.parse_all_token_trees() {
502 Err(err) => panic!(err),
504 let span = mk_sp(lo, p.last_span.hi);
507 // Mark the attrs as used
509 attr::mark_used(attr);
512 macros.push(ast::MacroDef {
513 ident: ast::Ident::with_empty_ctxt(name),
515 id: ast::DUMMY_NODE_ID,
517 imported_from: Some(item.ident),
518 // overridden in plugin/load.rs
521 allow_internal_unstable: false,
531 /// Look for a plugin registrar. Returns library path and symbol name.
532 pub fn find_plugin_registrar(&mut self, span: Span, name: &str)
533 -> Option<(PathBuf, String)> {
534 let ekrate = self.read_extension_crate(span, &CrateInfo {
535 name: name.to_string(),
536 ident: name.to_string(),
537 id: ast::DUMMY_NODE_ID,
541 if ekrate.target_only {
542 // Need to abort before syntax expansion.
543 let message = format!("plugin `{}` is not available for triple `{}` \
546 config::host_triple(),
547 self.sess.opts.target_triple);
548 span_err!(self.sess, span, E0456, "{}", &message[..]);
549 self.sess.abort_if_errors();
553 decoder::get_plugin_registrar_fn(ekrate.metadata.as_slice())
554 .map(|id| decoder::get_symbol_from_buf(ekrate.metadata.as_slice(), id));
556 match (ekrate.dylib.as_ref(), registrar) {
557 (Some(dylib), Some(reg)) => Some((dylib.to_path_buf(), reg)),
559 span_err!(self.sess, span, E0457,
560 "plugin `{}` only found in rlib format, but must be available \
563 // No need to abort because the loading code will just ignore this
571 fn register_statically_included_foreign_items(&mut self) {
572 let libs = self.sess.cstore.get_used_libraries();
573 for (lib, list) in self.foreign_item_map.iter() {
574 let is_static = libs.borrow().iter().any(|&(ref name, kind)| {
575 lib == name && kind == cstore::NativeStatic
579 self.sess.cstore.add_statically_included_foreign_item(*id);
585 fn inject_allocator_crate(&mut self) {
586 // Make sure that we actually need an allocator, if none of our
587 // dependencies need one then we definitely don't!
589 // Also, if one of our dependencies has an explicit allocator, then we
590 // also bail out as we don't need to implicitly inject one.
591 let mut needs_allocator = false;
592 let mut found_required_allocator = false;
593 self.sess.cstore.iter_crate_data(|cnum, data| {
594 needs_allocator = needs_allocator || data.needs_allocator();
595 if data.is_allocator() {
596 debug!("{} required by rlib and is an allocator", data.name());
597 self.inject_allocator_dependency(cnum);
598 found_required_allocator = found_required_allocator ||
599 data.explicitly_linked.get();
602 if !needs_allocator || found_required_allocator { return }
604 // At this point we've determined that we need an allocator and no
605 // previous allocator has been activated. We look through our outputs of
606 // crate types to see what kind of allocator types we may need.
608 // The main special output type here is that rlibs do **not** need an
609 // allocator linked in (they're just object files), only final products
610 // (exes, dylibs, staticlibs) need allocators.
611 let mut need_lib_alloc = false;
612 let mut need_exe_alloc = false;
613 for ct in self.sess.crate_types.borrow().iter() {
615 config::CrateTypeExecutable => need_exe_alloc = true,
616 config::CrateTypeDylib |
617 config::CrateTypeStaticlib => need_lib_alloc = true,
618 config::CrateTypeRlib => {}
621 if !need_lib_alloc && !need_exe_alloc { return }
623 // The default allocator crate comes from the custom target spec, and we
624 // choose between the standard library allocator or exe allocator. This
625 // distinction exists because the default allocator for binaries (where
626 // the world is Rust) is different than library (where the world is
627 // likely *not* Rust).
629 // If a library is being produced, but we're also flagged with `-C
630 // prefer-dynamic`, then we interpret this as a *Rust* dynamic library
631 // is being produced so we use the exe allocator instead.
633 // What this boils down to is:
635 // * Binaries use jemalloc
636 // * Staticlibs and Rust dylibs use system malloc
637 // * Rust dylibs used as dependencies to rust use jemalloc
638 let name = if need_lib_alloc && !self.sess.opts.cg.prefer_dynamic {
639 &self.sess.target.target.options.lib_allocation_crate
641 &self.sess.target.target.options.exe_allocation_crate
643 let (cnum, data, _) = self.resolve_crate(&None, name, name, None,
645 PathKind::Crate, false);
647 // To ensure that the `-Z allocation-crate=foo` option isn't abused, and
648 // to ensure that the allocator is indeed an allocator, we verify that
649 // the crate loaded here is indeed tagged #![allocator].
650 if !data.is_allocator() {
651 self.sess.err(&format!("the allocator crate `{}` is not tagged \
652 with #![allocator]", data.name()));
655 self.sess.injected_allocator.set(Some(cnum));
656 self.inject_allocator_dependency(cnum);
659 fn inject_allocator_dependency(&self, allocator: ast::CrateNum) {
660 // Before we inject any dependencies, make sure we don't inject a
661 // circular dependency by validating that this allocator crate doesn't
662 // transitively depend on any `#![needs_allocator]` crates.
663 validate(self, allocator, allocator);
665 // All crates tagged with `needs_allocator` do not explicitly depend on
666 // the allocator selected for this compile, but in order for this
667 // compilation to be successfully linked we need to inject a dependency
668 // (to order the crates on the command line correctly).
670 // Here we inject a dependency from all crates with #![needs_allocator]
671 // to the crate tagged with #![allocator] for this compilation unit.
672 self.sess.cstore.iter_crate_data(|cnum, data| {
673 if !data.needs_allocator() {
677 info!("injecting a dep from {} to {}", cnum, allocator);
678 let mut cnum_map = data.cnum_map.borrow_mut();
679 let remote_cnum = cnum_map.len() + 1;
680 let prev = cnum_map.insert(remote_cnum as ast::CrateNum, allocator);
681 assert!(prev.is_none());
684 fn validate(me: &CrateReader, krate: ast::CrateNum,
685 allocator: ast::CrateNum) {
686 let data = me.sess.cstore.get_crate_data(krate);
687 if data.needs_allocator() {
688 let krate_name = data.name();
689 let data = me.sess.cstore.get_crate_data(allocator);
690 let alloc_name = data.name();
691 me.sess.err(&format!("the allocator crate `{}` cannot depend \
692 on a crate that needs an allocator, but \
693 it depends on `{}`", alloc_name,
697 for (_, &dep) in data.cnum_map.borrow().iter() {
698 validate(me, dep, allocator);
704 impl<'a, 'b> LocalCrateReader<'a, 'b> {
705 pub fn new(sess: &'a Session, map: &'a hir_map::Map<'b>) -> LocalCrateReader<'a, 'b> {
708 creader: CrateReader::new(sess),
713 // Traverses an AST, reading all the information about use'd crates and
714 // extern libraries necessary for later resolving, typechecking, linking,
716 pub fn read_crates(&mut self, krate: &hir::Crate) {
717 self.process_crate(krate);
718 krate.visit_all_items(self);
719 self.creader.inject_allocator_crate();
721 if log_enabled!(log::INFO) {
722 dump_crates(&self.sess.cstore);
725 for &(ref name, kind) in &self.sess.opts.libs {
726 register_native_lib(self.sess, None, name.clone(), kind);
728 self.creader.register_statically_included_foreign_items();
731 fn process_crate(&self, c: &hir::Crate) {
732 for a in c.attrs.iter().filter(|m| m.name() == "link_args") {
733 match a.value_str() {
734 Some(ref linkarg) => self.sess.cstore.add_used_link_args(&linkarg),
735 None => { /* fallthrough */ }
740 fn process_item(&mut self, i: &hir::Item) {
742 hir::ItemExternCrate(_) => {
743 if !should_link_hir(i) {
747 match self.creader.extract_crate_info_hir(i) {
749 let (cnum, cmeta, _) = self.creader.resolve_crate(&None,
756 let def_id = self.ast_map.local_def_id(i.id);
757 let def_path = self.ast_map.def_path(def_id);
758 cmeta.update_local_def_path(def_path);
759 self.ast_map.with_path(i.id, |path| {
760 cmeta.update_local_path(path)
762 self.sess.cstore.add_extern_mod_stmt_cnum(info.id, cnum);
767 hir::ItemForeignMod(ref fm) => self.process_foreign_mod(i, fm),
772 fn process_foreign_mod(&mut self, i: &hir::Item, fm: &hir::ForeignMod) {
773 if fm.abi == abi::Rust || fm.abi == abi::RustIntrinsic || fm.abi == abi::PlatformIntrinsic {
777 // First, add all of the custom #[link_args] attributes
778 for m in i.attrs.iter().filter(|a| a.check_name("link_args")) {
779 if let Some(linkarg) = m.value_str() {
780 self.sess.cstore.add_used_link_args(&linkarg);
784 // Next, process all of the #[link(..)]-style arguments
785 for m in i.attrs.iter().filter(|a| a.check_name("link")) {
786 let items = match m.meta_item_list() {
790 let kind = items.iter().find(|k| {
792 }).and_then(|a| a.value_str());
793 let kind = match kind.as_ref().map(|s| &s[..]) {
794 Some("static") => cstore::NativeStatic,
795 Some("dylib") => cstore::NativeUnknown,
796 Some("framework") => cstore::NativeFramework,
798 span_err!(self.sess, m.span, E0458,
799 "unknown kind: `{}`", k);
800 cstore::NativeUnknown
802 None => cstore::NativeUnknown
804 let n = items.iter().find(|n| {
806 }).and_then(|a| a.value_str());
810 span_err!(self.sess, m.span, E0459,
811 "#[link(...)] specified without `name = \"foo\"`");
812 InternedString::new("foo")
815 register_native_lib(self.sess, Some(m.span), n.to_string(), kind);
818 // Finally, process the #[linked_from = "..."] attribute
819 for m in i.attrs.iter().filter(|a| a.check_name("linked_from")) {
820 let lib_name = match m.value_str() {
824 let list = self.creader.foreign_item_map.entry(lib_name.to_string())
825 .or_insert(Vec::new());
826 list.extend(fm.items.iter().map(|it| it.id));
831 /// Imports the codemap from an external crate into the codemap of the crate
832 /// currently being compiled (the "local crate").
834 /// The import algorithm works analogous to how AST items are inlined from an
835 /// external crate's metadata:
836 /// For every FileMap in the external codemap an 'inline' copy is created in the
837 /// local codemap. The correspondence relation between external and local
838 /// FileMaps is recorded in the `ImportedFileMap` objects returned from this
839 /// function. When an item from an external crate is later inlined into this
840 /// crate, this correspondence information is used to translate the span
841 /// information of the inlined item so that it refers the correct positions in
842 /// the local codemap (see `astencode::DecodeContext::tr_span()`).
844 /// The import algorithm in the function below will reuse FileMaps already
845 /// existing in the local codemap. For example, even if the FileMap of some
846 /// source file of libstd gets imported many times, there will only ever be
847 /// one FileMap object for the corresponding file in the local codemap.
849 /// Note that imported FileMaps do not actually contain the source code of the
850 /// file they represent, just information about length, line breaks, and
851 /// multibyte characters. This information is enough to generate valid debuginfo
852 /// for items inlined from other crates.
853 pub fn import_codemap(local_codemap: &codemap::CodeMap,
854 metadata: &MetadataBlob)
855 -> Vec<cstore::ImportedFileMap> {
856 let external_codemap = decoder::get_imported_filemaps(metadata.as_slice());
858 let imported_filemaps = external_codemap.into_iter().map(|filemap_to_import| {
859 // Try to find an existing FileMap that can be reused for the filemap to
860 // be imported. A FileMap is reusable if it is exactly the same, just
861 // positioned at a different offset within the codemap.
862 let reusable_filemap = {
866 .find(|fm| are_equal_modulo_startpos(&fm, &filemap_to_import))
867 .map(|rc| rc.clone())
870 match reusable_filemap {
872 cstore::ImportedFileMap {
873 original_start_pos: filemap_to_import.start_pos,
874 original_end_pos: filemap_to_import.end_pos,
875 translated_filemap: fm
879 // We can't reuse an existing FileMap, so allocate a new one
880 // containing the information we need.
881 let codemap::FileMap {
888 } = filemap_to_import;
890 let source_length = (end_pos - start_pos).to_usize();
892 // Translate line-start positions and multibyte character
893 // position into frame of reference local to file.
894 // `CodeMap::new_imported_filemap()` will then translate those
895 // coordinates to their new global frame of reference when the
896 // offset of the FileMap is known.
897 let mut lines = lines.into_inner();
898 for pos in &mut lines {
899 *pos = *pos - start_pos;
901 let mut multibyte_chars = multibyte_chars.into_inner();
902 for mbc in &mut multibyte_chars {
903 mbc.pos = mbc.pos - start_pos;
906 let local_version = local_codemap.new_imported_filemap(name,
910 cstore::ImportedFileMap {
911 original_start_pos: start_pos,
912 original_end_pos: end_pos,
913 translated_filemap: local_version
919 return imported_filemaps;
921 fn are_equal_modulo_startpos(fm1: &codemap::FileMap,
922 fm2: &codemap::FileMap)
924 if fm1.name != fm2.name {
928 let lines1 = fm1.lines.borrow();
929 let lines2 = fm2.lines.borrow();
931 if lines1.len() != lines2.len() {
935 for (&line1, &line2) in lines1.iter().zip(lines2.iter()) {
936 if (line1 - fm1.start_pos) != (line2 - fm2.start_pos) {
941 let multibytes1 = fm1.multibyte_chars.borrow();
942 let multibytes2 = fm2.multibyte_chars.borrow();
944 if multibytes1.len() != multibytes2.len() {
948 for (mb1, mb2) in multibytes1.iter().zip(multibytes2.iter()) {
949 if (mb1.bytes != mb2.bytes) ||
950 ((mb1.pos - fm1.start_pos) != (mb2.pos - fm2.start_pos)) {