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::feature_gate::UnstableFeatures;
50 use syntax::fold::Folder;
52 use syntax::parse::token;
55 pub fn compile_input(sess: Session,
56 cfg: ast::CrateConfig,
58 outdir: &Option<PathBuf>,
59 output: &Option<PathBuf>,
60 addl_plugins: Option<Vec<String>>,
61 control: CompileController) {
62 macro_rules! controller_entry_point{($point: ident, $tsess: expr, $make_state: expr) => ({
63 let state = $make_state;
64 (control.$point.callback)(state);
66 $tsess.abort_if_errors();
67 if control.$point.stop == Compilation::Stop {
72 // We need nested scopes here, because the intermediate results can keep
73 // large chunks of memory alive and we want to free them as soon as
74 // possible to keep the peak memory usage low
76 let (outputs, expanded_crate, id) = {
77 let krate = phase_1_parse_input(&sess, cfg, input);
79 controller_entry_point!(after_parse,
81 CompileState::state_after_parse(input,
86 let outputs = build_output_filenames(input,
91 let id = link::find_crate_name(Some(&sess),
95 = match phase_2_configure_and_expand(&sess,
103 (outputs, expanded_crate, id)
106 controller_entry_point!(after_expand,
108 CompileState::state_after_expand(input,
114 let expanded_crate = assign_node_ids(&sess, expanded_crate);
116 let lcx = LoweringContext::new(&sess, Some(&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,
161 (control.after_analysis.callback)(state);
163 tcx.sess.abort_if_errors();
164 if control.after_analysis.stop == Compilation::Stop {
169 if log_enabled!(::log::INFO) {
170 println!("Pre-trans");
171 tcx.print_debug_stats();
173 let trans = phase_4_translate_to_llvm(tcx, analysis);
175 if log_enabled!(::log::INFO) {
176 println!("Post-trans");
177 tcx.print_debug_stats();
180 // Discard interned strings as they are no longer required.
181 token::get_ident_interner().clear();
187 let (outputs, trans) = if let Ok(out) = result {
193 phase_5_run_llvm_passes(&sess, &trans, &outputs);
195 controller_entry_point!(after_llvm,
197 CompileState::state_after_llvm(input,
202 phase_6_link_output(&sess, &trans, &outputs);
205 /// The name used for source code that doesn't originate in a file
206 /// (e.g. source from stdin or a string)
207 pub fn anon_src() -> String {
211 pub fn source_name(input: &Input) -> String {
213 // FIXME (#9639): This needs to handle non-utf8 paths
214 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
215 Input::Str(_) => anon_src()
219 /// CompileController is used to customise compilation, it allows compilation to
220 /// be stopped and/or to call arbitrary code at various points in compilation.
221 /// It also allows for various flags to be set to influence what information gets
222 /// collected during compilation.
224 /// This is a somewhat higher level controller than a Session - the Session
225 /// controls what happens in each phase, whereas the CompileController controls
226 /// whether a phase is run at all and whether other code (from outside the
227 /// the compiler) is run between phases.
229 /// Note that if compilation is set to stop and a callback is provided for a
230 /// given entry point, the callback is called before compilation is stopped.
232 /// Expect more entry points to be added in the future.
233 pub struct CompileController<'a> {
234 pub after_parse: PhaseController<'a>,
235 pub after_expand: PhaseController<'a>,
236 pub after_write_deps: PhaseController<'a>,
237 pub after_analysis: PhaseController<'a>,
238 pub after_llvm: PhaseController<'a>,
240 pub make_glob_map: resolve::MakeGlobMap,
243 impl<'a> CompileController<'a> {
244 pub fn basic() -> CompileController<'a> {
246 after_parse: PhaseController::basic(),
247 after_expand: PhaseController::basic(),
248 after_write_deps: PhaseController::basic(),
249 after_analysis: PhaseController::basic(),
250 after_llvm: PhaseController::basic(),
251 make_glob_map: resolve::MakeGlobMap::No,
256 pub struct PhaseController<'a> {
257 pub stop: Compilation,
258 pub callback: Box<Fn(CompileState) -> () + 'a>,
261 impl<'a> PhaseController<'a> {
262 pub fn basic() -> PhaseController<'a> {
264 stop: Compilation::Continue,
265 callback: box |_| {},
270 /// State that is passed to a callback. What state is available depends on when
271 /// during compilation the callback is made. See the various constructor methods
272 /// (`state_*`) in the impl to see which data is provided for any given entry point.
273 pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
274 pub input: &'a Input,
275 pub session: &'a Session,
276 pub cfg: Option<&'a ast::CrateConfig>,
277 pub krate: Option<&'a ast::Crate>,
278 pub crate_name: Option<&'a str>,
279 pub output_filenames: Option<&'a OutputFilenames>,
280 pub out_dir: Option<&'a Path>,
281 pub expanded_crate: Option<&'a ast::Crate>,
282 pub hir_crate: Option<&'a hir::Crate>,
283 pub ast_map: Option<&'a hir_map::Map<'ast>>,
284 pub analysis: Option<&'a ty::CrateAnalysis<'a>>,
285 pub tcx: Option<&'a ty::ctxt<'tcx>>,
286 pub lcx: Option<&'a LoweringContext<'a>>,
287 pub trans: Option<&'a trans::CrateTranslation>,
290 impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
291 fn empty(input: &'a Input,
292 session: &'a Session,
293 out_dir: &'a Option<PathBuf>)
294 -> CompileState<'a, 'ast, 'tcx> {
298 out_dir: out_dir.as_ref().map(|s| &**s),
302 output_filenames: None,
303 expanded_crate: None,
313 fn state_after_parse(input: &'a Input,
314 session: &'a Session,
315 out_dir: &'a Option<PathBuf>,
316 krate: &'a ast::Crate)
317 -> CompileState<'a, 'ast, 'tcx> {
320 .. CompileState::empty(input, session, out_dir)
324 fn state_after_expand(input: &'a Input,
325 session: &'a Session,
326 out_dir: &'a Option<PathBuf>,
327 expanded_crate: &'a ast::Crate,
329 -> CompileState<'a, 'ast, 'tcx> {
331 crate_name: Some(crate_name),
332 expanded_crate: Some(expanded_crate),
333 .. CompileState::empty(input, session, out_dir)
337 fn state_after_write_deps(input: &'a Input,
338 session: &'a Session,
339 out_dir: &'a Option<PathBuf>,
340 ast_map: &'a hir_map::Map<'ast>,
341 krate: &'a ast::Crate,
342 hir_crate: &'a hir::Crate,
344 lcx: &'a LoweringContext<'a>)
345 -> CompileState<'a, 'ast, 'tcx> {
347 crate_name: Some(crate_name),
348 ast_map: Some(ast_map),
350 hir_crate: Some(hir_crate),
352 .. CompileState::empty(input, session, out_dir)
356 fn state_after_analysis(input: &'a Input,
357 session: &'a Session,
358 out_dir: &'a Option<PathBuf>,
359 krate: &'a ast::Crate,
360 hir_crate: &'a hir::Crate,
361 analysis: &'a ty::CrateAnalysis,
362 tcx: &'a ty::ctxt<'tcx>,
363 lcx: &'a LoweringContext<'a>,
365 -> CompileState<'a, 'ast, 'tcx> {
367 analysis: Some(analysis),
370 hir_crate: Some(hir_crate),
372 crate_name: Some(crate_name),
373 .. CompileState::empty(input, session, out_dir)
378 fn state_after_llvm(input: &'a Input,
379 session: &'a Session,
380 out_dir: &'a Option<PathBuf>,
381 trans: &'a trans::CrateTranslation)
382 -> CompileState<'a, 'ast, 'tcx> {
385 .. CompileState::empty(input, session, out_dir)
390 pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
392 // These may be left in an incoherent state after a previous compile.
393 // `clear_tables` and `get_ident_interner().clear()` can be used to free
394 // memory, but they do not restore the initial state.
395 syntax::ext::mtwt::reset_tables();
396 token::reset_ident_interner();
398 let krate = time(sess.time_passes(), "parsing", || {
400 Input::File(ref file) => {
401 parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
403 Input::Str(ref src) => {
404 parse::parse_crate_from_source_str(anon_src().to_string(),
412 if sess.opts.debugging_opts.ast_json_noexpand {
413 println!("{}", json::as_json(&krate));
416 if let Some(ref s) = sess.opts.show_span {
417 syntax::show_span::run(sess.diagnostic(), s, &krate);
423 // For continuing compilation after a parsed crate has been
426 /// Run the "early phases" of the compiler: initial `cfg` processing,
427 /// loading compiler plugins (including those from `addl_plugins`),
428 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
429 /// harness if one is to be provided and injection of a dependency on the
430 /// standard library and prelude.
432 /// Returns `None` if we're aborting after handling -W help.
433 pub fn phase_2_configure_and_expand(sess: &Session,
434 mut krate: ast::Crate,
436 addl_plugins: Option<Vec<String>>)
437 -> Option<ast::Crate> {
438 let time_passes = sess.time_passes();
440 // strip before anything else because crate metadata may use #[cfg_attr]
441 // and so macros can depend on configuration variables, such as
443 // #[macro_use] #[cfg(foo)]
444 // mod bar { macro_rules! baz!(() => {{}}) }
446 // baz! should not use this definition unless foo is enabled.
448 let mut feature_gated_cfgs = vec![];
449 krate = time(time_passes, "configuration 1", ||
450 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate,
451 &mut feature_gated_cfgs));
453 *sess.crate_types.borrow_mut() =
454 collect_crate_types(sess, &krate.attrs);
455 *sess.crate_metadata.borrow_mut() =
456 collect_crate_metadata(sess, &krate.attrs);
458 time(time_passes, "recursion limit", || {
459 middle::recursion_limit::update_recursion_limit(sess, &krate);
462 time(time_passes, "gated macro checking", || {
464 syntax::feature_gate::check_crate_macros(sess.codemap(),
465 &sess.parse_sess.span_diagnostic,
468 // these need to be set "early" so that expansion sees `quote` if enabled.
469 *sess.features.borrow_mut() = features;
470 sess.abort_if_errors();
474 krate = time(time_passes, "crate injection", ||
475 syntax::std_inject::maybe_inject_crates_ref(krate,
476 sess.opts.alt_std_name.clone()));
478 let macros = time(time_passes, "macro loading", ||
479 metadata::macro_import::read_macro_defs(sess, &krate));
481 let mut addl_plugins = Some(addl_plugins);
482 let registrars = time(time_passes, "plugin loading", ||
483 plugin::load::load_plugins(sess, &krate, addl_plugins.take().unwrap()));
485 let mut registry = Registry::new(sess, &krate);
487 time(time_passes, "plugin registration", || {
488 if sess.features.borrow().rustc_diagnostic_macros {
489 registry.register_macro("__diagnostic_used",
490 diagnostics::plugin::expand_diagnostic_used);
491 registry.register_macro("__register_diagnostic",
492 diagnostics::plugin::expand_register_diagnostic);
493 registry.register_macro("__build_diagnostic_array",
494 diagnostics::plugin::expand_build_diagnostic_array);
497 for registrar in registrars {
498 registry.args_hidden = Some(registrar.args);
499 (registrar.fun)(&mut registry);
503 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
504 llvm_passes, attributes, .. } = registry;
507 let mut ls = sess.lint_store.borrow_mut();
508 for pass in early_lint_passes {
509 ls.register_early_pass(Some(sess), true, pass);
511 for pass in late_lint_passes {
512 ls.register_late_pass(Some(sess), true, pass);
515 for (name, to) in lint_groups {
516 ls.register_group(Some(sess), true, name, to);
519 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
520 *sess.plugin_attributes.borrow_mut() = attributes.clone();
523 // Lint plugins are registered; now we can process command line flags.
524 if sess.opts.describe_lints {
525 super::describe_lints(&*sess.lint_store.borrow(), true);
528 sess.lint_store.borrow_mut().process_command_line(sess);
530 // Abort if there are errors from lint processing or a plugin registrar.
531 sess.abort_if_errors();
533 krate = time(time_passes, "expansion", || {
534 // Windows dlls do not have rpaths, so they don't know how to find their
535 // dependencies. It's up to us to tell the system where to find all the
536 // dependent dlls. Note that this uses cfg!(windows) as opposed to
537 // targ_cfg because syntax extensions are always loaded for the host
538 // compiler, not for the target.
539 let mut _old_path = OsString::new();
541 _old_path = env::var_os("PATH").unwrap_or(_old_path);
542 let mut new_path = sess.host_filesearch(PathKind::All)
543 .get_dylib_search_paths();
544 new_path.extend(env::split_paths(&_old_path));
545 env::set_var("PATH", &env::join_paths(new_path).unwrap());
547 let features = sess.features.borrow();
548 let cfg = syntax::ext::expand::ExpansionConfig {
549 crate_name: crate_name.to_string(),
550 features: Some(&features),
551 recursion_limit: sess.recursion_limit.get(),
552 trace_mac: sess.opts.debugging_opts.trace_macros,
554 let ret = syntax::ext::expand::expand_crate(&sess.parse_sess,
558 &mut feature_gated_cfgs,
561 env::set_var("PATH", &_old_path);
566 // Needs to go *after* expansion to be able to check the results
567 // of macro expansion. This runs before #[cfg] to try to catch as
568 // much as possible (e.g. help the programmer avoid platform
569 // specific differences)
570 time(time_passes, "complete gated feature checking 1", || {
572 syntax::feature_gate::check_crate(sess.codemap(),
573 &sess.parse_sess.span_diagnostic,
575 sess.opts.unstable_features);
576 *sess.features.borrow_mut() = features;
577 sess.abort_if_errors();
580 // JBC: make CFG processing part of expansion to avoid this problem:
582 // strip again, in case expansion added anything with a #[cfg].
583 krate = time(time_passes, "configuration 2", ||
584 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate,
585 &mut feature_gated_cfgs));
587 time(time_passes, "gated configuration checking", || {
588 let features = sess.features.borrow();
589 feature_gated_cfgs.sort();
590 feature_gated_cfgs.dedup();
591 for cfg in &feature_gated_cfgs {
592 cfg.check_and_emit(sess.diagnostic(), &features);
596 krate = time(time_passes, "maybe building test harness", ||
597 syntax::test::modify_for_testing(&sess.parse_sess,
602 krate = time(time_passes, "prelude injection", ||
603 syntax::std_inject::maybe_inject_prelude(&sess.parse_sess, krate));
605 time(time_passes, "checking that all macro invocations are gone", ||
606 syntax::ext::expand::check_for_macros(&sess.parse_sess, &krate));
608 time(time_passes, "checking for inline asm in case the target doesn't support it", ||
609 middle::check_no_asm::check_crate(sess, &krate));
611 // One final feature gating of the true AST that gets compiled
612 // later, to make sure we've got everything (e.g. configuration
613 // can insert new attributes via `cfg_attr`)
614 time(time_passes, "complete gated feature checking 2", || {
616 syntax::feature_gate::check_crate(sess.codemap(),
617 &sess.parse_sess.span_diagnostic,
619 sess.opts.unstable_features);
620 *sess.features.borrow_mut() = features;
621 sess.abort_if_errors();
627 pub fn assign_node_ids(sess: &Session,
628 krate: ast::Crate) -> ast::Crate {
629 struct NodeIdAssigner<'a> {
633 impl<'a> Folder for NodeIdAssigner<'a> {
634 fn new_id(&mut self, old_id: ast::NodeId) -> ast::NodeId {
635 assert_eq!(old_id, ast::DUMMY_NODE_ID);
636 self.sess.next_node_id()
640 let krate = time(sess.time_passes(),
641 "assigning node ids",
642 || NodeIdAssigner { sess: sess }.fold_crate(krate));
644 if sess.opts.debugging_opts.ast_json {
645 println!("{}", json::as_json(&krate));
651 pub fn make_map<'ast>(sess: &Session,
652 forest: &'ast mut front::map::Forest)
653 -> front::map::Map<'ast> {
654 // Construct the 'ast'-map
655 let map = time(sess.time_passes(),
657 move || front::map::map_crate(forest));
662 /// Run the resolution, typechecking, region checking and other
663 /// miscellaneous analysis passes on the crate. Return various
664 /// structures carrying the results of the analysis.
665 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
666 ast_map: front::map::Map<'tcx>,
667 arenas: &'tcx ty::CtxtArenas<'tcx>,
669 make_glob_map: resolve::MakeGlobMap,
672 where F: for<'a> FnOnce(&'a ty::ctxt<'tcx>,
673 ty::CrateAnalysis) -> R
675 let time_passes = sess.time_passes();
676 let krate = ast_map.krate();
678 time(time_passes, "external crate/lib resolution", ||
679 LocalCrateReader::new(sess, &ast_map).read_crates(krate));
681 let lang_items = time(time_passes, "language item collection", ||
682 middle::lang_items::collect_language_items(&sess, &ast_map));
684 let resolve::CrateMap {
692 time(time_passes, "resolution",
693 || resolve::resolve_crate(sess, &ast_map, make_glob_map));
695 // Discard MTWT tables that aren't required past resolution.
696 if !sess.opts.debugging_opts.keep_mtwt_tables {
697 syntax::ext::mtwt::clear_tables();
700 let named_region_map = time(time_passes, "lifetime resolution",
701 || middle::resolve_lifetime::krate(sess, krate, &def_map));
703 time(time_passes, "looking for entry point",
704 || middle::entry::find_entry_point(sess, &ast_map));
706 sess.plugin_registrar_fn.set(
707 time(time_passes, "looking for plugin registrar", ||
708 plugin::build::find_plugin_registrar(
709 sess.diagnostic(), krate)));
711 let region_map = time(time_passes, "region resolution", ||
712 middle::region::resolve_crate(sess, krate));
714 time(time_passes, "loop checking", ||
715 middle::check_loop::check_crate(sess, krate));
717 time(time_passes, "static item recursion checking", ||
718 middle::check_static_recursion::check_crate(sess, krate, &def_map, &ast_map));
720 ty::ctxt::create_and_enter(sess,
728 stability::Index::new(krate),
731 // passes are timed inside typeck
732 typeck::check_crate(tcx, trait_map);
734 time(time_passes, "const checking", ||
735 middle::check_const::check_crate(tcx));
737 let (exported_items, public_items) =
738 time(time_passes, "privacy checking", ||
739 rustc_privacy::check_crate(tcx, &export_map, external_exports));
741 // Do not move this check past lint
742 time(time_passes, "stability index", ||
743 tcx.stability.borrow_mut().build(tcx, krate, &public_items));
745 time(time_passes, "intrinsic checking", ||
746 middle::intrinsicck::check_crate(tcx));
748 time(time_passes, "effect checking", ||
749 middle::effect::check_crate(tcx));
751 time(time_passes, "match checking", ||
752 middle::check_match::check_crate(tcx));
754 match tcx.sess.opts.unstable_features {
755 UnstableFeatures::Disallow => {
756 // use this as a shorthand for beta/stable, and skip
757 // MIR construction there until known regressions are
760 UnstableFeatures::Allow | UnstableFeatures::Cheat => {
762 time(time_passes, "MIR dump", ||
763 mir::mir_map::build_mir_for_crate(tcx));
767 time(time_passes, "liveness checking", ||
768 middle::liveness::check_crate(tcx));
770 time(time_passes, "borrow checking", ||
771 borrowck::check_crate(tcx));
773 time(time_passes, "rvalue checking", ||
774 middle::check_rvalues::check_crate(tcx, krate));
776 // Avoid overwhelming user with errors if type checking failed.
777 // I'm not sure how helpful this is, to be honest, but it avoids a
778 // lot of annoying errors in the compile-fail tests (basically,
779 // lint warnings and so on -- kindck used to do this abort, but
780 // kindck is gone now). -nmatsakis
781 tcx.sess.abort_if_errors();
784 time(time_passes, "reachability checking", ||
785 reachable::find_reachable(tcx, &exported_items));
787 time(time_passes, "death checking", || {
788 middle::dead::check_crate(tcx,
793 let ref lib_features_used =
794 time(time_passes, "stability checking", ||
795 stability::check_unstable_api_usage(tcx));
797 time(time_passes, "unused lib feature checking", ||
798 stability::check_unused_or_stable_features(
799 &tcx.sess, lib_features_used));
801 time(time_passes, "lint checking", ||
802 lint::check_crate(tcx, krate, &exported_items));
804 // The above three passes generate errors w/o aborting
805 tcx.sess.abort_if_errors();
807 f(tcx, ty::CrateAnalysis {
808 export_map: export_map,
809 exported_items: exported_items,
810 public_items: public_items,
811 reachable: reachable_map,
818 /// Run the translation phase to LLVM, after which the AST and analysis can
820 pub fn phase_4_translate_to_llvm(tcx: &ty::ctxt, analysis: ty::CrateAnalysis)
821 -> trans::CrateTranslation {
822 let time_passes = tcx.sess.time_passes();
824 time(time_passes, "resolving dependency formats", ||
825 dependency_format::calculate(&tcx.sess));
827 // Option dance to work around the lack of stack once closures.
828 time(time_passes, "translation", move ||
829 trans::trans_crate(tcx, analysis))
832 /// Run LLVM itself, producing a bitcode file, assembly file or object file
833 /// as a side effect.
834 pub fn phase_5_run_llvm_passes(sess: &Session,
835 trans: &trans::CrateTranslation,
836 outputs: &OutputFilenames) {
837 if sess.opts.cg.no_integrated_as {
838 let mut map = HashMap::new();
839 map.insert(OutputType::Assembly, None);
840 time(sess.time_passes(), "LLVM passes", ||
841 write::run_passes(sess, trans, &map, outputs));
843 write::run_assembler(sess, outputs);
845 // Remove assembly source, unless --save-temps was specified
846 if !sess.opts.cg.save_temps {
847 fs::remove_file(&outputs.temp_path(OutputType::Assembly)).unwrap();
850 time(sess.time_passes(), "LLVM passes", ||
851 write::run_passes(sess,
853 &sess.opts.output_types,
857 sess.abort_if_errors();
860 /// Run the linker on any artifacts that resulted from the LLVM run.
861 /// This should produce either a finished executable or library.
862 pub fn phase_6_link_output(sess: &Session,
863 trans: &trans::CrateTranslation,
864 outputs: &OutputFilenames) {
865 time(sess.time_passes(), "linking", ||
866 link::link_binary(sess,
869 &trans.link.crate_name));
872 fn escape_dep_filename(filename: &str) -> String {
873 // Apparently clang and gcc *only* escape spaces:
874 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
875 filename.replace(" ", "\\ ")
878 fn write_out_deps(sess: &Session, outputs: &OutputFilenames, id: &str) {
879 let mut out_filenames = Vec::new();
880 for output_type in sess.opts.output_types.keys() {
881 let file = outputs.path(*output_type);
884 for output in sess.crate_types.borrow().iter() {
885 let p = link::filename_for_input(sess, *output, id,
887 out_filenames.push(p);
890 _ => { out_filenames.push(file); }
894 // Write out dependency rules to the dep-info file if requested
895 if !sess.opts.output_types.contains_key(&OutputType::DepInfo) {
898 let deps_filename = outputs.path(OutputType::DepInfo);
900 let result = (|| -> io::Result<()> {
901 // Build a list of files used to compile the output and
902 // write Makefile-compatible dependency rules
903 let files: Vec<String> = sess.codemap().files.borrow()
905 .filter(|fmap| fmap.is_real_file())
906 .filter(|fmap| !fmap.is_imported())
907 .map(|fmap| escape_dep_filename(&fmap.name))
909 let mut file = try!(fs::File::create(&deps_filename));
910 for path in &out_filenames {
912 "{}: {}\n\n", path.display(), files.join(" ")));
915 // Emit a fake target for each input file to the compilation. This
916 // prevents `make` from spitting out an error if a file is later
917 // deleted. For more info see #28735
919 try!(writeln!(file, "{}:", path));
927 sess.fatal(&format!("error writing dependencies to `{}`: {}",
928 deps_filename.display(), e));
933 pub fn collect_crate_types(session: &Session,
934 attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
935 // Unconditionally collect crate types from attributes to make them used
936 let attr_types: Vec<config::CrateType> = attrs.iter().filter_map(|a| {
937 if a.check_name("crate_type") {
938 match a.value_str() {
939 Some(ref n) if *n == "rlib" => {
940 Some(config::CrateTypeRlib)
942 Some(ref n) if *n == "dylib" => {
943 Some(config::CrateTypeDylib)
945 Some(ref n) if *n == "lib" => {
946 Some(config::default_lib_output())
948 Some(ref n) if *n == "staticlib" => {
949 Some(config::CrateTypeStaticlib)
951 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
953 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
956 "invalid `crate_type` \
961 session.span_err(a.span, "`crate_type` requires a value");
962 session.note("for example: `#![crate_type=\"lib\"]`");
971 // If we're generating a test executable, then ignore all other output
972 // styles at all other locations
973 if session.opts.test {
974 return vec!(config::CrateTypeExecutable)
977 // Only check command line flags if present. If no types are specified by
978 // command line, then reuse the empty `base` Vec to hold the types that
979 // will be found in crate attributes.
980 let mut base = session.opts.crate_types.clone();
982 base.extend(attr_types);
984 base.push(link::default_output_for_target(session));
990 base.into_iter().filter(|crate_type| {
991 let res = !link::invalid_output_for_target(session, *crate_type);
994 session.warn(&format!("dropping unsupported crate type `{}` \
996 *crate_type, session.opts.target_triple));
1003 pub fn collect_crate_metadata(session: &Session,
1004 _attrs: &[ast::Attribute]) -> Vec<String> {
1005 session.opts.cg.metadata.clone()
1008 pub fn build_output_filenames(input: &Input,
1009 odir: &Option<PathBuf>,
1010 ofile: &Option<PathBuf>,
1011 attrs: &[ast::Attribute],
1013 -> OutputFilenames {
1016 // "-" as input file will cause the parser to read from stdin so we
1017 // have to make up a name
1018 // We want to toss everything after the final '.'
1019 let dirpath = match *odir {
1020 Some(ref d) => d.clone(),
1021 None => PathBuf::new()
1024 // If a crate name is present, we use it as the link name
1025 let stem = sess.opts.crate_name.clone().or_else(|| {
1026 attr::find_crate_name(attrs).map(|n| n.to_string())
1027 }).unwrap_or(input.filestem());
1030 out_directory: dirpath,
1032 single_output_file: None,
1033 extra: sess.opts.cg.extra_filename.clone(),
1034 outputs: sess.opts.output_types.clone(),
1038 Some(ref out_file) => {
1039 let unnamed_output_types = sess.opts.output_types.values()
1040 .filter(|a| a.is_none())
1042 let ofile = if unnamed_output_types > 1 {
1043 sess.warn("ignoring specified output filename because multiple \
1044 outputs were requested");
1047 Some(out_file.clone())
1050 sess.warn("ignoring --out-dir flag due to -o flag.");
1053 let cur_dir = Path::new("");
1056 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1057 out_filestem: out_file.file_stem().unwrap_or(OsStr::new(""))
1058 .to_str().unwrap().to_string(),
1059 single_output_file: ofile,
1060 extra: sess.opts.cg.extra_filename.clone(),
1061 outputs: sess.opts.output_types.clone(),