1 // Copyright 2014-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 //! The Rust compiler.
15 //! This API is completely unstable and subject to change.
17 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18 html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19 html_root_url = "https://doc.rust-lang.org/nightly/")]
22 #![feature(box_syntax)]
25 use std::io::prelude::*;
26 use std::io::{self, Cursor};
31 use rustc_data_structures::owning_ref::{ErasedBoxRef, OwningRef};
32 use rustc_data_structures::sync::Lrc;
33 use ar::{Archive, Builder, Header};
34 use flate2::Compression;
35 use flate2::write::DeflateEncoder;
37 use syntax::symbol::Symbol;
38 use rustc::hir::def_id::LOCAL_CRATE;
39 use rustc::session::{Session, CompileIncomplete};
40 use rustc::session::config::{CrateType, OutputFilenames, PrintRequest};
41 use rustc::ty::TyCtxt;
42 use rustc::ty::maps::Providers;
43 use rustc::middle::cstore::EncodedMetadata;
44 use rustc::middle::cstore::MetadataLoader;
45 use rustc::dep_graph::DepGraph;
46 use rustc_back::target::Target;
47 use rustc_mir::monomorphize::collector;
48 use link::{build_link_meta, out_filename};
50 pub trait TransCrate {
51 fn init(&self, _sess: &Session) {}
52 fn print(&self, _req: PrintRequest, _sess: &Session) {}
53 fn target_features(&self, _sess: &Session) -> Vec<Symbol> { vec![] }
54 fn print_passes(&self) {}
55 fn print_version(&self) {}
56 fn diagnostics(&self) -> &[(&'static str, &'static str)] { &[] }
58 fn metadata_loader(&self) -> Box<MetadataLoader>;
59 fn provide(&self, _providers: &mut Providers);
60 fn provide_extern(&self, _providers: &mut Providers);
61 fn trans_crate<'a, 'tcx>(
63 tcx: TyCtxt<'a, 'tcx, 'tcx>,
64 rx: mpsc::Receiver<Box<Any + Send>>
67 /// This is called on the returned `Box<Any>` from `trans_crate`
71 /// Panics when the passed `Box<Any>` was not returned by `trans_crate`.
72 fn join_trans_and_link(
77 outputs: &OutputFilenames,
78 ) -> Result<(), CompileIncomplete>;
81 pub struct DummyTransCrate;
83 impl TransCrate for DummyTransCrate {
84 fn metadata_loader(&self) -> Box<MetadataLoader> {
85 box DummyMetadataLoader(())
88 fn provide(&self, _providers: &mut Providers) {
89 bug!("DummyTransCrate::provide");
92 fn provide_extern(&self, _providers: &mut Providers) {
93 bug!("DummyTransCrate::provide_extern");
96 fn trans_crate<'a, 'tcx>(
98 _tcx: TyCtxt<'a, 'tcx, 'tcx>,
99 _rx: mpsc::Receiver<Box<Any + Send>>
101 bug!("DummyTransCrate::trans_crate");
104 fn join_trans_and_link(
108 _dep_graph: &DepGraph,
109 _outputs: &OutputFilenames,
110 ) -> Result<(), CompileIncomplete> {
111 bug!("DummyTransCrate::join_trans_and_link");
115 pub struct DummyMetadataLoader(());
117 impl MetadataLoader for DummyMetadataLoader {
118 fn get_rlib_metadata(
122 ) -> Result<ErasedBoxRef<[u8]>, String> {
123 bug!("DummyMetadataLoader::get_rlib_metadata");
126 fn get_dylib_metadata(
130 ) -> Result<ErasedBoxRef<[u8]>, String> {
131 bug!("DummyMetadataLoader::get_dylib_metadata");
135 pub struct NoLlvmMetadataLoader;
137 impl MetadataLoader for NoLlvmMetadataLoader {
138 fn get_rlib_metadata(&self, _: &Target, filename: &Path) -> Result<ErasedBoxRef<[u8]>, String> {
139 let file = File::open(filename)
140 .map_err(|e| format!("metadata file open err: {:?}", e))?;
141 let mut archive = Archive::new(file);
143 while let Some(entry_result) = archive.next_entry() {
144 let mut entry = entry_result
145 .map_err(|e| format!("metadata section read err: {:?}", e))?;
146 if entry.header().identifier() == "rust.metadata.bin" {
147 let mut buf = Vec::new();
148 io::copy(&mut entry, &mut buf).unwrap();
149 let buf: OwningRef<Vec<u8>, [u8]> = OwningRef::new(buf).into();
150 return Ok(buf.map_owner_box().erase_owner());
154 Err("Couldn't find metadata section".to_string())
157 fn get_dylib_metadata(
161 ) -> Result<ErasedBoxRef<[u8]>, String> {
162 // FIXME: Support reading dylibs from llvm enabled rustc
163 self.get_rlib_metadata(_target, _filename)
167 pub struct MetadataOnlyTransCrate(());
168 pub struct OngoingCrateTranslation {
169 metadata: EncodedMetadata,
170 metadata_version: Vec<u8>,
174 impl MetadataOnlyTransCrate {
175 pub fn new() -> Box<TransCrate> {
176 box MetadataOnlyTransCrate(())
180 impl TransCrate for MetadataOnlyTransCrate {
181 fn init(&self, sess: &Session) {
182 for cty in sess.opts.crate_types.iter() {
184 CrateType::CrateTypeRlib | CrateType::CrateTypeDylib |
185 CrateType::CrateTypeExecutable => {},
187 sess.parse_sess.span_diagnostic.warn(
188 &format!("LLVM unsupported, so output type {} is not supported", cty)
195 fn metadata_loader(&self) -> Box<MetadataLoader> {
196 box NoLlvmMetadataLoader
199 fn provide(&self, providers: &mut Providers) {
200 ::symbol_names::provide(providers);
201 providers.target_features_enabled = |_tcx, _id| {
202 Lrc::new(Vec::new()) // Just a dummy
205 fn provide_extern(&self, _providers: &mut Providers) {}
207 fn trans_crate<'a, 'tcx>(
209 tcx: TyCtxt<'a, 'tcx, 'tcx>,
210 _rx: mpsc::Receiver<Box<Any + Send>>
212 use rustc_mir::monomorphize::item::MonoItem;
214 ::check_for_rustc_errors_attr(tcx);
215 ::symbol_names_test::report_symbol_names(tcx);
216 ::rustc_incremental::assert_dep_graph(tcx);
217 ::rustc_incremental::assert_module_sources::assert_module_sources(tcx);
218 ::rustc_mir::monomorphize::assert_symbols_are_distinct(tcx,
219 collector::collect_crate_mono_items(
221 collector::MonoItemCollectionMode::Eager
224 ::rustc::middle::dependency_format::calculate(tcx);
225 let _ = tcx.link_args(LOCAL_CRATE);
226 let _ = tcx.native_libraries(LOCAL_CRATE);
228 collector::collect_crate_mono_items(
230 collector::MonoItemCollectionMode::Eager
233 MonoItem::Fn(inst) => {
234 let def_id = inst.def_id();
235 if def_id.is_local() {
236 let _ = tcx.export_name(def_id);
237 let _ = tcx.contains_extern_indicator(def_id);
238 let _ = inst.def.is_inline(tcx);
239 let _ = tcx.trans_fn_attrs(def_id);
245 tcx.sess.abort_if_errors();
247 let link_meta = build_link_meta(tcx.crate_hash(LOCAL_CRATE));
248 let metadata = tcx.encode_metadata(&link_meta);
250 box OngoingCrateTranslation {
252 metadata_version: tcx.metadata_encoding_version().to_vec(),
253 crate_name: tcx.crate_name(LOCAL_CRATE),
257 fn join_trans_and_link(
261 _dep_graph: &DepGraph,
262 outputs: &OutputFilenames,
263 ) -> Result<(), CompileIncomplete> {
264 let trans = trans.downcast::<OngoingCrateTranslation>()
265 .expect("Expected MetadataOnlyTransCrate's OngoingCrateTranslation, found Box<Any>");
266 for &crate_type in sess.opts.crate_types.iter() {
267 if crate_type != CrateType::CrateTypeRlib && crate_type != CrateType::CrateTypeDylib {
271 out_filename(sess, crate_type, &outputs, &trans.crate_name.as_str());
272 let mut compressed = trans.metadata_version.clone();
273 let metadata = if crate_type == CrateType::CrateTypeDylib {
274 DeflateEncoder::new(&mut compressed, Compression::fast())
275 .write_all(&trans.metadata.raw_data)
279 &trans.metadata.raw_data
281 let mut builder = Builder::new(File::create(&output_name).unwrap());
282 let header = Header::new("rust.metadata.bin".to_string(), metadata.len() as u64);
283 builder.append(&header, Cursor::new(metadata)).unwrap();
286 sess.abort_if_errors();
287 if !sess.opts.crate_types.contains(&CrateType::CrateTypeRlib)
288 && !sess.opts.crate_types.contains(&CrateType::CrateTypeDylib)
290 sess.fatal("Executables are not supported by the metadata-only backend.");