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.
12 use rustc::front::map as hir_map;
14 use rustc::session::Session;
15 use rustc::session::config::{self, Input, OutputFilenames, OutputType};
16 use rustc::session::search_paths::PathKind;
19 use rustc::metadata::creader::LocalCrateReader;
20 use rustc::middle::{stability, ty, reachable};
21 use rustc::middle::dependency_format;
23 use rustc::plugin::registry::Registry;
25 use rustc::util::common::time;
26 use rustc_borrowck as borrowck;
27 use rustc_resolve as resolve;
28 use rustc_trans::back::link;
29 use rustc_trans::back::write;
30 use rustc_trans::trans;
31 use rustc_typeck as typeck;
34 use rustc_front::lowering::{lower_crate, LoweringContext};
35 use super::Compilation;
39 use std::collections::HashMap;
41 use std::ffi::{OsString, OsStr};
43 use std::io::{self, Write};
44 use std::path::{Path, PathBuf};
45 use syntax::ast::{self, NodeIdAssigner};
47 use syntax::attr::AttrMetaMethods;
48 use syntax::diagnostics;
49 use syntax::fold::Folder;
51 use syntax::parse::token;
54 pub fn compile_input(sess: Session,
55 cfg: ast::CrateConfig,
57 outdir: &Option<PathBuf>,
58 output: &Option<PathBuf>,
59 addl_plugins: Option<Vec<String>>,
60 control: CompileController) {
61 macro_rules! controller_entry_point{($point: ident, $tsess: expr, $make_state: expr) => ({
62 let state = $make_state;
63 (control.$point.callback)(state);
65 $tsess.abort_if_errors();
66 if control.$point.stop == Compilation::Stop {
71 // We need nested scopes here, because the intermediate results can keep
72 // large chunks of memory alive and we want to free them as soon as
73 // possible to keep the peak memory usage low
75 let (outputs, expanded_crate, id) = {
76 let krate = phase_1_parse_input(&sess, cfg, input);
78 controller_entry_point!(after_parse,
80 CompileState::state_after_parse(input,
85 let outputs = build_output_filenames(input,
90 let id = link::find_crate_name(Some(&sess),
94 = match phase_2_configure_and_expand(&sess,
102 (outputs, expanded_crate, id)
105 controller_entry_point!(after_expand,
107 CompileState::state_after_expand(input,
113 let expanded_crate = assign_node_ids(&sess, expanded_crate);
116 let lcx = LoweringContext::new(foo, &sess, &expanded_crate);
117 let mut hir_forest = time(sess.time_passes(),
118 "lowering ast -> hir",
119 || hir_map::Forest::new(lower_crate(&lcx, &expanded_crate)));
120 let arenas = ty::CtxtArenas::new();
121 let ast_map = make_map(&sess, &mut hir_forest);
123 write_out_deps(&sess, &outputs, &id);
125 controller_entry_point!(after_write_deps,
127 CompileState::state_after_write_deps(input,
136 time(sess.time_passes(), "attribute checking", || {
137 front::check_attr::check_crate(&sess, &expanded_crate);
140 time(sess.time_passes(), "early lint checks", || {
141 lint::check_ast_crate(&sess, &expanded_crate)
144 phase_3_run_analysis_passes(&sess,
148 control.make_glob_map,
152 let state = CompileState::state_after_analysis(input,
160 (control.after_analysis.callback)(state);
162 tcx.sess.abort_if_errors();
163 if control.after_analysis.stop == Compilation::Stop {
168 if log_enabled!(::log::INFO) {
169 println!("Pre-trans");
170 tcx.print_debug_stats();
172 let trans = phase_4_translate_to_llvm(tcx, analysis);
174 if log_enabled!(::log::INFO) {
175 println!("Post-trans");
176 tcx.print_debug_stats();
179 // Discard interned strings as they are no longer required.
180 token::get_ident_interner().clear();
186 let (outputs, trans) = if let Ok(out) = result {
192 phase_5_run_llvm_passes(&sess, &trans, &outputs);
194 controller_entry_point!(after_llvm,
196 CompileState::state_after_llvm(input,
201 phase_6_link_output(&sess, &trans, &outputs);
204 /// The name used for source code that doesn't originate in a file
205 /// (e.g. source from stdin or a string)
206 pub fn anon_src() -> String {
210 pub fn source_name(input: &Input) -> String {
212 // FIXME (#9639): This needs to handle non-utf8 paths
213 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
214 Input::Str(_) => anon_src()
218 /// CompileController is used to customise compilation, it allows compilation to
219 /// be stopped and/or to call arbitrary code at various points in compilation.
220 /// It also allows for various flags to be set to influence what information gets
221 /// collected during compilation.
223 /// This is a somewhat higher level controller than a Session - the Session
224 /// controls what happens in each phase, whereas the CompileController controls
225 /// whether a phase is run at all and whether other code (from outside the
226 /// the compiler) is run between phases.
228 /// Note that if compilation is set to stop and a callback is provided for a
229 /// given entry point, the callback is called before compilation is stopped.
231 /// Expect more entry points to be added in the future.
232 pub struct CompileController<'a> {
233 pub after_parse: PhaseController<'a>,
234 pub after_expand: PhaseController<'a>,
235 pub after_write_deps: PhaseController<'a>,
236 pub after_analysis: PhaseController<'a>,
237 pub after_llvm: PhaseController<'a>,
239 pub make_glob_map: resolve::MakeGlobMap,
242 impl<'a> CompileController<'a> {
243 pub fn basic() -> CompileController<'a> {
245 after_parse: PhaseController::basic(),
246 after_expand: PhaseController::basic(),
247 after_write_deps: PhaseController::basic(),
248 after_analysis: PhaseController::basic(),
249 after_llvm: PhaseController::basic(),
250 make_glob_map: resolve::MakeGlobMap::No,
255 pub struct PhaseController<'a> {
256 pub stop: Compilation,
257 pub callback: Box<Fn(CompileState) -> () + 'a>,
260 impl<'a> PhaseController<'a> {
261 pub fn basic() -> PhaseController<'a> {
263 stop: Compilation::Continue,
264 callback: box |_| {},
269 /// State that is passed to a callback. What state is available depends on when
270 /// during compilation the callback is made. See the various constructor methods
271 /// (`state_*`) in the impl to see which data is provided for any given entry point.
272 pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
273 pub input: &'a Input,
274 pub session: &'a Session,
275 pub cfg: Option<&'a ast::CrateConfig>,
276 pub krate: Option<&'a ast::Crate>,
277 pub crate_name: Option<&'a str>,
278 pub output_filenames: Option<&'a OutputFilenames>,
279 pub out_dir: Option<&'a Path>,
280 pub expanded_crate: Option<&'a ast::Crate>,
281 pub hir_crate: Option<&'a hir::Crate>,
282 pub ast_map: Option<&'a hir_map::Map<'ast>>,
283 pub analysis: Option<&'a ty::CrateAnalysis>,
284 pub tcx: Option<&'a ty::ctxt<'tcx>>,
285 pub lcx: Option<&'a LoweringContext<'a, 'tcx>>,
286 pub trans: Option<&'a trans::CrateTranslation>,
289 impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
290 fn empty(input: &'a Input,
291 session: &'a Session,
292 out_dir: &'a Option<PathBuf>)
293 -> CompileState<'a, 'ast, 'tcx> {
297 out_dir: out_dir.as_ref().map(|s| &**s),
301 output_filenames: None,
302 expanded_crate: None,
312 fn state_after_parse(input: &'a Input,
313 session: &'a Session,
314 out_dir: &'a Option<PathBuf>,
315 krate: &'a ast::Crate)
316 -> CompileState<'a, 'ast, 'tcx> {
319 .. CompileState::empty(input, session, out_dir)
323 fn state_after_expand(input: &'a Input,
324 session: &'a Session,
325 out_dir: &'a Option<PathBuf>,
326 expanded_crate: &'a ast::Crate,
328 -> CompileState<'a, 'ast, 'tcx> {
330 crate_name: Some(crate_name),
331 expanded_crate: Some(expanded_crate),
332 .. CompileState::empty(input, session, out_dir)
336 fn state_after_write_deps(input: &'a Input,
337 session: &'a Session,
338 out_dir: &'a Option<PathBuf>,
339 ast_map: &'a hir_map::Map<'ast>,
340 krate: &'a ast::Crate,
341 hir_crate: &'a hir::Crate,
343 lcx: &'a LoweringContext<'a, 'tcx>)
344 -> CompileState<'a, 'ast, 'tcx> {
346 crate_name: Some(crate_name),
347 ast_map: Some(ast_map),
349 hir_crate: Some(hir_crate),
351 .. CompileState::empty(input, session, out_dir)
355 fn state_after_analysis(input: &'a Input,
356 session: &'a Session,
357 out_dir: &'a Option<PathBuf>,
358 krate: &'a ast::Crate,
359 hir_crate: &'a hir::Crate,
360 analysis: &'a ty::CrateAnalysis,
361 tcx: &'a ty::ctxt<'tcx>,
362 lcx: &'a LoweringContext<'a, 'tcx>)
363 -> CompileState<'a, 'ast, 'tcx> {
365 analysis: Some(analysis),
368 hir_crate: Some(hir_crate),
370 .. CompileState::empty(input, session, out_dir)
375 fn state_after_llvm(input: &'a Input,
376 session: &'a Session,
377 out_dir: &'a Option<PathBuf>,
378 trans: &'a trans::CrateTranslation)
379 -> CompileState<'a, 'ast, 'tcx> {
382 .. CompileState::empty(input, session, out_dir)
387 pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
389 // These may be left in an incoherent state after a previous compile.
390 // `clear_tables` and `get_ident_interner().clear()` can be used to free
391 // memory, but they do not restore the initial state.
392 syntax::ext::mtwt::reset_tables();
393 token::reset_ident_interner();
395 let krate = time(sess.time_passes(), "parsing", || {
397 Input::File(ref file) => {
398 parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
400 Input::Str(ref src) => {
401 parse::parse_crate_from_source_str(anon_src().to_string(),
409 if sess.opts.debugging_opts.ast_json_noexpand {
410 println!("{}", json::as_json(&krate));
413 if let Some(ref s) = sess.opts.show_span {
414 syntax::show_span::run(sess.diagnostic(), s, &krate);
420 // For continuing compilation after a parsed crate has been
423 /// Run the "early phases" of the compiler: initial `cfg` processing,
424 /// loading compiler plugins (including those from `addl_plugins`),
425 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
426 /// harness if one is to be provided and injection of a dependency on the
427 /// standard library and prelude.
429 /// Returns `None` if we're aborting after handling -W help.
430 pub fn phase_2_configure_and_expand(sess: &Session,
431 mut krate: ast::Crate,
433 addl_plugins: Option<Vec<String>>)
434 -> Option<ast::Crate> {
435 let time_passes = sess.time_passes();
437 // strip before anything else because crate metadata may use #[cfg_attr]
438 // and so macros can depend on configuration variables, such as
440 // #[macro_use] #[cfg(foo)]
441 // mod bar { macro_rules! baz!(() => {{}}) }
443 // baz! should not use this definition unless foo is enabled.
445 let mut feature_gated_cfgs = vec![];
446 krate = time(time_passes, "configuration 1", ||
447 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate,
448 &mut feature_gated_cfgs));
450 *sess.crate_types.borrow_mut() =
451 collect_crate_types(sess, &krate.attrs);
452 *sess.crate_metadata.borrow_mut() =
453 collect_crate_metadata(sess, &krate.attrs);
455 time(time_passes, "recursion limit", || {
456 middle::recursion_limit::update_recursion_limit(sess, &krate);
459 time(time_passes, "gated macro checking", || {
461 syntax::feature_gate::check_crate_macros(sess.codemap(),
462 &sess.parse_sess.span_diagnostic,
465 // these need to be set "early" so that expansion sees `quote` if enabled.
466 *sess.features.borrow_mut() = features;
467 sess.abort_if_errors();
471 krate = time(time_passes, "crate injection", ||
472 syntax::std_inject::maybe_inject_crates_ref(krate,
473 sess.opts.alt_std_name.clone()));
475 let macros = time(time_passes, "macro loading", ||
476 metadata::macro_import::read_macro_defs(sess, &krate));
478 let mut addl_plugins = Some(addl_plugins);
479 let registrars = time(time_passes, "plugin loading", ||
480 plugin::load::load_plugins(sess, &krate, addl_plugins.take().unwrap()));
482 let mut registry = Registry::new(sess, &krate);
484 time(time_passes, "plugin registration", || {
485 if sess.features.borrow().rustc_diagnostic_macros {
486 registry.register_macro("__diagnostic_used",
487 diagnostics::plugin::expand_diagnostic_used);
488 registry.register_macro("__register_diagnostic",
489 diagnostics::plugin::expand_register_diagnostic);
490 registry.register_macro("__build_diagnostic_array",
491 diagnostics::plugin::expand_build_diagnostic_array);
494 for registrar in registrars {
495 registry.args_hidden = Some(registrar.args);
496 (registrar.fun)(&mut registry);
500 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
501 llvm_passes, attributes, .. } = registry;
504 let mut ls = sess.lint_store.borrow_mut();
505 for pass in early_lint_passes {
506 ls.register_early_pass(Some(sess), true, pass);
508 for pass in late_lint_passes {
509 ls.register_late_pass(Some(sess), true, pass);
512 for (name, to) in lint_groups {
513 ls.register_group(Some(sess), true, name, to);
516 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
517 *sess.plugin_attributes.borrow_mut() = attributes.clone();
520 // Lint plugins are registered; now we can process command line flags.
521 if sess.opts.describe_lints {
522 super::describe_lints(&*sess.lint_store.borrow(), true);
525 sess.lint_store.borrow_mut().process_command_line(sess);
527 // Abort if there are errors from lint processing or a plugin registrar.
528 sess.abort_if_errors();
530 krate = time(time_passes, "expansion", || {
531 // Windows dlls do not have rpaths, so they don't know how to find their
532 // dependencies. It's up to us to tell the system where to find all the
533 // dependent dlls. Note that this uses cfg!(windows) as opposed to
534 // targ_cfg because syntax extensions are always loaded for the host
535 // compiler, not for the target.
536 let mut _old_path = OsString::new();
538 _old_path = env::var_os("PATH").unwrap_or(_old_path);
539 let mut new_path = sess.host_filesearch(PathKind::All)
540 .get_dylib_search_paths();
541 new_path.extend(env::split_paths(&_old_path));
542 env::set_var("PATH", &env::join_paths(new_path).unwrap());
544 let features = sess.features.borrow();
545 let cfg = syntax::ext::expand::ExpansionConfig {
546 crate_name: crate_name.to_string(),
547 features: Some(&features),
548 recursion_limit: sess.recursion_limit.get(),
549 trace_mac: sess.opts.debugging_opts.trace_macros,
551 let ret = syntax::ext::expand::expand_crate(&sess.parse_sess,
555 &mut feature_gated_cfgs,
558 env::set_var("PATH", &_old_path);
563 // Needs to go *after* expansion to be able to check the results
564 // of macro expansion. This runs before #[cfg] to try to catch as
565 // much as possible (e.g. help the programmer avoid platform
566 // specific differences)
567 time(time_passes, "complete gated feature checking 1", || {
569 syntax::feature_gate::check_crate(sess.codemap(),
570 &sess.parse_sess.span_diagnostic,
572 sess.opts.unstable_features);
573 *sess.features.borrow_mut() = features;
574 sess.abort_if_errors();
577 // JBC: make CFG processing part of expansion to avoid this problem:
579 // strip again, in case expansion added anything with a #[cfg].
580 krate = time(time_passes, "configuration 2", ||
581 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate,
582 &mut feature_gated_cfgs));
584 time(time_passes, "gated configuration checking", || {
585 let features = sess.features.borrow();
586 feature_gated_cfgs.sort();
587 feature_gated_cfgs.dedup();
588 for cfg in &feature_gated_cfgs {
589 cfg.check_and_emit(sess.diagnostic(), &features);
593 krate = time(time_passes, "maybe building test harness", ||
594 syntax::test::modify_for_testing(&sess.parse_sess,
599 krate = time(time_passes, "prelude injection", ||
600 syntax::std_inject::maybe_inject_prelude(&sess.parse_sess, krate));
602 time(time_passes, "checking that all macro invocations are gone", ||
603 syntax::ext::expand::check_for_macros(&sess.parse_sess, &krate));
605 time(time_passes, "checking for inline asm in case the target doesn't support it", ||
606 middle::check_no_asm::check_crate(sess, &krate));
608 // One final feature gating of the true AST that gets compiled
609 // later, to make sure we've got everything (e.g. configuration
610 // can insert new attributes via `cfg_attr`)
611 time(time_passes, "complete gated feature checking 2", || {
613 syntax::feature_gate::check_crate(sess.codemap(),
614 &sess.parse_sess.span_diagnostic,
616 sess.opts.unstable_features);
617 *sess.features.borrow_mut() = features;
618 sess.abort_if_errors();
624 pub fn assign_node_ids(sess: &Session,
625 krate: ast::Crate) -> ast::Crate {
626 struct NodeIdAssigner<'a> {
630 impl<'a> Folder for NodeIdAssigner<'a> {
631 fn new_id(&mut self, old_id: ast::NodeId) -> ast::NodeId {
632 assert_eq!(old_id, ast::DUMMY_NODE_ID);
633 self.sess.next_node_id()
637 let krate = time(sess.time_passes(),
638 "assigning node ids",
639 || NodeIdAssigner { sess: sess }.fold_crate(krate));
641 if sess.opts.debugging_opts.ast_json {
642 println!("{}", json::as_json(&krate));
648 pub fn make_map<'ast>(sess: &Session,
649 forest: &'ast mut front::map::Forest)
650 -> front::map::Map<'ast> {
651 // Construct the 'ast'-map
652 let map = time(sess.time_passes(),
654 move || front::map::map_crate(forest));
659 /// Run the resolution, typechecking, region checking and other
660 /// miscellaneous analysis passes on the crate. Return various
661 /// structures carrying the results of the analysis.
662 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
663 ast_map: front::map::Map<'tcx>,
664 arenas: &'tcx ty::CtxtArenas<'tcx>,
666 make_glob_map: resolve::MakeGlobMap,
669 where F: for<'a> FnOnce(&'a ty::ctxt<'tcx>,
670 ty::CrateAnalysis) -> R
672 let time_passes = sess.time_passes();
673 let krate = ast_map.krate();
675 time(time_passes, "external crate/lib resolution", ||
676 LocalCrateReader::new(sess, &ast_map).read_crates(krate));
678 let lang_items = time(time_passes, "language item collection", ||
679 middle::lang_items::collect_language_items(&sess, &ast_map));
681 let resolve::CrateMap {
689 time(time_passes, "resolution",
690 || resolve::resolve_crate(sess, &ast_map, make_glob_map));
692 // Discard MTWT tables that aren't required past resolution.
693 if !sess.opts.debugging_opts.keep_mtwt_tables {
694 syntax::ext::mtwt::clear_tables();
697 let named_region_map = time(time_passes, "lifetime resolution",
698 || middle::resolve_lifetime::krate(sess, krate, &def_map));
700 time(time_passes, "looking for entry point",
701 || middle::entry::find_entry_point(sess, &ast_map));
703 sess.plugin_registrar_fn.set(
704 time(time_passes, "looking for plugin registrar", ||
705 plugin::build::find_plugin_registrar(
706 sess.diagnostic(), krate)));
708 let region_map = time(time_passes, "region resolution", ||
709 middle::region::resolve_crate(sess, krate));
711 time(time_passes, "loop checking", ||
712 middle::check_loop::check_crate(sess, krate));
714 time(time_passes, "static item recursion checking", ||
715 middle::check_static_recursion::check_crate(sess, krate, &def_map, &ast_map));
717 ty::ctxt::create_and_enter(sess,
725 stability::Index::new(krate),
728 // passes are timed inside typeck
729 typeck::check_crate(tcx, trait_map);
731 time(time_passes, "const checking", ||
732 middle::check_const::check_crate(tcx));
734 let (exported_items, public_items) =
735 time(time_passes, "privacy checking", ||
736 rustc_privacy::check_crate(tcx, &export_map, external_exports));
738 // Do not move this check past lint
739 time(time_passes, "stability index", ||
740 tcx.stability.borrow_mut().build(tcx, krate, &public_items));
742 time(time_passes, "intrinsic checking", ||
743 middle::intrinsicck::check_crate(tcx));
745 time(time_passes, "effect checking", ||
746 middle::effect::check_crate(tcx));
748 time(time_passes, "match checking", ||
749 middle::check_match::check_crate(tcx));
752 time(time_passes, "MIR dump", ||
753 mir::mir_map::build_mir_for_crate(tcx));
755 time(time_passes, "liveness checking", ||
756 middle::liveness::check_crate(tcx));
758 time(time_passes, "borrow checking", ||
759 borrowck::check_crate(tcx));
761 time(time_passes, "rvalue checking", ||
762 middle::check_rvalues::check_crate(tcx, krate));
764 // Avoid overwhelming user with errors if type checking failed.
765 // I'm not sure how helpful this is, to be honest, but it avoids a
766 // lot of annoying errors in the compile-fail tests (basically,
767 // lint warnings and so on -- kindck used to do this abort, but
768 // kindck is gone now). -nmatsakis
769 tcx.sess.abort_if_errors();
772 time(time_passes, "reachability checking", ||
773 reachable::find_reachable(tcx, &exported_items));
775 time(time_passes, "death checking", || {
776 middle::dead::check_crate(tcx,
781 let ref lib_features_used =
782 time(time_passes, "stability checking", ||
783 stability::check_unstable_api_usage(tcx));
785 time(time_passes, "unused lib feature checking", ||
786 stability::check_unused_or_stable_features(
787 &tcx.sess, lib_features_used));
789 time(time_passes, "lint checking", ||
790 lint::check_crate(tcx, krate, &exported_items));
792 // The above three passes generate errors w/o aborting
793 tcx.sess.abort_if_errors();
795 f(tcx, ty::CrateAnalysis {
796 export_map: export_map,
797 exported_items: exported_items,
798 public_items: public_items,
799 reachable: reachable_map,
806 /// Run the translation phase to LLVM, after which the AST and analysis can
808 pub fn phase_4_translate_to_llvm(tcx: &ty::ctxt, analysis: ty::CrateAnalysis)
809 -> trans::CrateTranslation {
810 let time_passes = tcx.sess.time_passes();
812 time(time_passes, "resolving dependency formats", ||
813 dependency_format::calculate(&tcx.sess));
815 // Option dance to work around the lack of stack once closures.
816 time(time_passes, "translation", move ||
817 trans::trans_crate(tcx, analysis))
820 /// Run LLVM itself, producing a bitcode file, assembly file or object file
821 /// as a side effect.
822 pub fn phase_5_run_llvm_passes(sess: &Session,
823 trans: &trans::CrateTranslation,
824 outputs: &OutputFilenames) {
825 if sess.opts.cg.no_integrated_as {
826 let mut map = HashMap::new();
827 map.insert(OutputType::Assembly, None);
828 time(sess.time_passes(), "LLVM passes", ||
829 write::run_passes(sess, trans, &map, outputs));
831 write::run_assembler(sess, outputs);
833 // Remove assembly source, unless --save-temps was specified
834 if !sess.opts.cg.save_temps {
835 fs::remove_file(&outputs.temp_path(OutputType::Assembly)).unwrap();
838 time(sess.time_passes(), "LLVM passes", ||
839 write::run_passes(sess,
841 &sess.opts.output_types,
845 sess.abort_if_errors();
848 /// Run the linker on any artifacts that resulted from the LLVM run.
849 /// This should produce either a finished executable or library.
850 pub fn phase_6_link_output(sess: &Session,
851 trans: &trans::CrateTranslation,
852 outputs: &OutputFilenames) {
853 time(sess.time_passes(), "linking", ||
854 link::link_binary(sess,
857 &trans.link.crate_name));
860 fn escape_dep_filename(filename: &str) -> String {
861 // Apparently clang and gcc *only* escape spaces:
862 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
863 filename.replace(" ", "\\ ")
866 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) {
867 let mut out_filenames = Vec::new();
868 for output_type in sess.opts.output_types.keys() {
869 let file = outputs.path(*output_type);
872 for output in sess.crate_types.borrow().iter() {
873 let p = link::filename_for_input(sess, *output, id,
875 out_filenames.push(p);
878 _ => { out_filenames.push(file); }
882 // Write out dependency rules to the dep-info file if requested
883 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
886 let deps_filename = outputs.path(OutputType::DepInfo);
888 let result = (|| -> io::Result<()> {
889 // Build a list of files used to compile the output and
890 // write Makefile-compatible dependency rules
891 let files: Vec<String> = sess.codemap().files.borrow()
893 .filter(|fmap| fmap.is_real_file())
894 .filter(|fmap| !fmap.is_imported())
895 .map(|fmap| escape_dep_filename(&fmap.name))
897 let mut file = try!(fs::File::create(&deps_filename));
898 for path in &out_filenames {
900 "{}: {}\n\n", path.display(), files.join(" ")));
903 // Emit a fake target for each input file to the compilation. This
904 // prevents `make` from spitting out an error if a file is later
905 // deleted. For more info see #28735
907 try!(writeln!(file, "{}:", path));
915 sess.fatal(&format!("error writing dependencies to `{}`: {}",
916 deps_filename.display(), e));
921 pub fn collect_crate_types(session: &Session,
922 attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
923 // Unconditionally collect crate types from attributes to make them used
924 let attr_types: Vec<config::CrateType> = attrs.iter().filter_map(|a| {
925 if a.check_name("crate_type") {
926 match a.value_str() {
927 Some(ref n) if *n == "rlib" => {
928 Some(config::CrateTypeRlib)
930 Some(ref n) if *n == "dylib" => {
931 Some(config::CrateTypeDylib)
933 Some(ref n) if *n == "lib" => {
934 Some(config::default_lib_output())
936 Some(ref n) if *n == "staticlib" => {
937 Some(config::CrateTypeStaticlib)
939 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
941 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
944 "invalid `crate_type` \
949 session.span_err(a.span, "`crate_type` requires a value");
950 session.note("for example: `#![crate_type=\"lib\"]`");
959 // If we're generating a test executable, then ignore all other output
960 // styles at all other locations
961 if session.opts.test {
962 return vec!(config::CrateTypeExecutable)
965 // Only check command line flags if present. If no types are specified by
966 // command line, then reuse the empty `base` Vec to hold the types that
967 // will be found in crate attributes.
968 let mut base = session.opts.crate_types.clone();
970 base.extend(attr_types);
972 base.push(link::default_output_for_target(session));
978 base.into_iter().filter(|crate_type| {
979 let res = !link::invalid_output_for_target(session, *crate_type);
982 session.warn(&format!("dropping unsupported crate type `{}` \
984 *crate_type, session.opts.target_triple));
991 pub fn collect_crate_metadata(session: &Session,
992 _attrs: &[ast::Attribute]) -> Vec<String> {
993 session.opts.cg.metadata.clone()
996 pub fn build_output_filenames(input: &Input,
997 odir: &Option<PathBuf>,
998 ofile: &Option<PathBuf>,
999 attrs: &[ast::Attribute],
1001 -> OutputFilenames {
1004 // "-" as input file will cause the parser to read from stdin so we
1005 // have to make up a name
1006 // We want to toss everything after the final '.'
1007 let dirpath = match *odir {
1008 Some(ref d) => d.clone(),
1009 None => PathBuf::new()
1012 // If a crate name is present, we use it as the link name
1013 let stem = sess.opts.crate_name.clone().or_else(|| {
1014 attr::find_crate_name(attrs).map(|n| n.to_string())
1015 }).unwrap_or(input.filestem());
1018 out_directory: dirpath,
1020 single_output_file: None,
1021 extra: sess.opts.cg.extra_filename.clone(),
1022 outputs: sess.opts.output_types.clone(),
1026 Some(ref out_file) => {
1027 let unnamed_output_types = sess.opts.output_types.values()
1028 .filter(|a| a.is_none())
1030 let ofile = if unnamed_output_types > 1 {
1031 sess.warn("ignoring specified output filename because multiple \
1032 outputs were requested");
1035 Some(out_file.clone())
1038 sess.warn("ignoring --out-dir flag due to -o flag.");
1041 let cur_dir = Path::new("");
1044 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1045 out_filestem: out_file.file_stem().unwrap_or(OsStr::new(""))
1046 .to_str().unwrap().to_string(),
1047 single_output_file: ofile,
1048 extra: sess.opts.cg.extra_filename.clone(),
1049 outputs: sess.opts.output_types.clone(),