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};
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;
35 use super::Compilation;
40 use std::ffi::{OsString, OsStr};
42 use std::io::{self, Write};
43 use std::path::{Path, PathBuf};
46 use syntax::attr::AttrMetaMethods;
47 use syntax::diagnostics;
48 use syntax::fold::Folder;
50 use syntax::parse::token;
53 pub fn compile_input(sess: Session,
54 cfg: ast::CrateConfig,
56 outdir: &Option<PathBuf>,
57 output: &Option<PathBuf>,
58 addl_plugins: Option<Vec<String>>,
59 control: CompileController) {
60 macro_rules! controller_entry_point{($point: ident, $tsess: expr, $make_state: expr) => ({
61 let state = $make_state;
62 (control.$point.callback)(state);
64 $tsess.abort_if_errors();
65 if control.$point.stop == Compilation::Stop {
70 // We need nested scopes here, because the intermediate results can keep
71 // large chunks of memory alive and we want to free them as soon as
72 // possible to keep the peak memory usage low
73 let (sess, result) = {
74 let (outputs, expanded_crate, id) = {
75 let krate = phase_1_parse_input(&sess, cfg, input);
77 controller_entry_point!(after_parse,
79 CompileState::state_after_parse(input,
84 let outputs = build_output_filenames(input,
89 let id = link::find_crate_name(Some(&sess),
93 = match phase_2_configure_and_expand(&sess,
101 (outputs, expanded_crate, id)
104 controller_entry_point!(after_expand,
106 CompileState::state_after_expand(input,
112 let expanded_crate = assign_node_ids(&sess, expanded_crate);
114 let mut hir_forest = time(sess.time_passes(),
115 "lowering ast -> hir",
116 || hir_map::Forest::new(lower_crate(&expanded_crate)));
117 let arenas = ty::CtxtArenas::new();
118 let ast_map = make_map(&sess, &mut hir_forest);
120 write_out_deps(&sess, input, &outputs, &id[..]);
122 controller_entry_point!(after_write_deps,
124 CompileState::state_after_write_deps(input,
132 time(sess.time_passes(), "early lint checks", || {
133 lint::check_ast_crate(&sess, &expanded_crate)
136 phase_3_run_analysis_passes(sess,
140 control.make_glob_map,
144 let state = CompileState::state_after_analysis(input,
151 (control.after_analysis.callback)(state);
153 tcx.sess.abort_if_errors();
154 if control.after_analysis.stop == Compilation::Stop {
159 if log_enabled!(::log::INFO) {
160 println!("Pre-trans");
161 tcx.print_debug_stats();
163 let trans = phase_4_translate_to_llvm(tcx, analysis);
165 if log_enabled!(::log::INFO) {
166 println!("Post-trans");
167 tcx.print_debug_stats();
170 // Discard interned strings as they are no longer required.
171 token::get_ident_interner().clear();
177 let (outputs, trans) = if let Ok(out) = result {
183 phase_5_run_llvm_passes(&sess, &trans, &outputs);
185 controller_entry_point!(after_llvm,
187 CompileState::state_after_llvm(input,
192 phase_6_link_output(&sess, &trans, &outputs);
195 /// The name used for source code that doesn't originate in a file
196 /// (e.g. source from stdin or a string)
197 pub fn anon_src() -> String {
201 pub fn source_name(input: &Input) -> String {
203 // FIXME (#9639): This needs to handle non-utf8 paths
204 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
205 Input::Str(_) => anon_src()
209 /// CompileController is used to customise compilation, it allows compilation to
210 /// be stopped and/or to call arbitrary code at various points in compilation.
211 /// It also allows for various flags to be set to influence what information gets
212 /// collected during compilation.
214 /// This is a somewhat higher level controller than a Session - the Session
215 /// controls what happens in each phase, whereas the CompileController controls
216 /// whether a phase is run at all and whether other code (from outside the
217 /// the compiler) is run between phases.
219 /// Note that if compilation is set to stop and a callback is provided for a
220 /// given entry point, the callback is called before compilation is stopped.
222 /// Expect more entry points to be added in the future.
223 pub struct CompileController<'a> {
224 pub after_parse: PhaseController<'a>,
225 pub after_expand: PhaseController<'a>,
226 pub after_write_deps: PhaseController<'a>,
227 pub after_analysis: PhaseController<'a>,
228 pub after_llvm: PhaseController<'a>,
230 pub make_glob_map: resolve::MakeGlobMap,
233 impl<'a> CompileController<'a> {
234 pub fn basic() -> CompileController<'a> {
236 after_parse: PhaseController::basic(),
237 after_expand: PhaseController::basic(),
238 after_write_deps: PhaseController::basic(),
239 after_analysis: PhaseController::basic(),
240 after_llvm: PhaseController::basic(),
241 make_glob_map: resolve::MakeGlobMap::No,
246 pub struct PhaseController<'a> {
247 pub stop: Compilation,
248 pub callback: Box<Fn(CompileState) -> () + 'a>,
251 impl<'a> PhaseController<'a> {
252 pub fn basic() -> PhaseController<'a> {
254 stop: Compilation::Continue,
255 callback: box |_| {},
260 /// State that is passed to a callback. What state is available depends on when
261 /// during compilation the callback is made. See the various constructor methods
262 /// (`state_*`) in the impl to see which data is provided for any given entry point.
263 pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
264 pub input: &'a Input,
265 pub session: &'a Session,
266 pub cfg: Option<&'a ast::CrateConfig>,
267 pub krate: Option<&'a ast::Crate>,
268 pub crate_name: Option<&'a str>,
269 pub output_filenames: Option<&'a OutputFilenames>,
270 pub out_dir: Option<&'a Path>,
271 pub expanded_crate: Option<&'a ast::Crate>,
272 pub hir_crate: Option<&'a hir::Crate>,
273 pub ast_map: Option<&'a hir_map::Map<'ast>>,
274 pub analysis: Option<&'a ty::CrateAnalysis>,
275 pub tcx: Option<&'a ty::ctxt<'tcx>>,
276 pub trans: Option<&'a trans::CrateTranslation>,
279 impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
280 fn empty(input: &'a Input,
281 session: &'a Session,
282 out_dir: &'a Option<PathBuf>)
283 -> CompileState<'a, 'ast, 'tcx> {
287 out_dir: out_dir.as_ref().map(|s| &**s),
291 output_filenames: None,
292 expanded_crate: None,
301 fn state_after_parse(input: &'a Input,
302 session: &'a Session,
303 out_dir: &'a Option<PathBuf>,
304 krate: &'a ast::Crate)
305 -> CompileState<'a, 'ast, 'tcx> {
308 .. CompileState::empty(input, session, out_dir)
312 fn state_after_expand(input: &'a Input,
313 session: &'a Session,
314 out_dir: &'a Option<PathBuf>,
315 expanded_crate: &'a ast::Crate,
317 -> CompileState<'a, 'ast, 'tcx> {
319 crate_name: Some(crate_name),
320 expanded_crate: Some(expanded_crate),
321 .. CompileState::empty(input, session, out_dir)
325 fn state_after_write_deps(input: &'a Input,
326 session: &'a Session,
327 out_dir: &'a Option<PathBuf>,
328 ast_map: &'a hir_map::Map<'ast>,
329 krate: &'a ast::Crate,
330 hir_crate: &'a hir::Crate,
332 -> CompileState<'a, 'ast, 'tcx> {
334 crate_name: Some(crate_name),
335 ast_map: Some(ast_map),
337 hir_crate: Some(hir_crate),
338 .. CompileState::empty(input, session, out_dir)
342 fn state_after_analysis(input: &'a Input,
343 session: &'a Session,
344 out_dir: &'a Option<PathBuf>,
345 krate: &'a ast::Crate,
346 hir_crate: &'a hir::Crate,
347 analysis: &'a ty::CrateAnalysis,
348 tcx: &'a ty::ctxt<'tcx>)
349 -> CompileState<'a, 'ast, 'tcx> {
351 analysis: Some(analysis),
354 hir_crate: Some(hir_crate),
355 .. CompileState::empty(input, session, out_dir)
360 fn state_after_llvm(input: &'a Input,
361 session: &'a Session,
362 out_dir: &'a Option<PathBuf>,
363 trans: &'a trans::CrateTranslation)
364 -> CompileState<'a, 'ast, 'tcx> {
367 .. CompileState::empty(input, session, out_dir)
372 pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
374 // These may be left in an incoherent state after a previous compile.
375 // `clear_tables` and `get_ident_interner().clear()` can be used to free
376 // memory, but they do not restore the initial state.
377 syntax::ext::mtwt::reset_tables();
378 token::reset_ident_interner();
380 let krate = time(sess.time_passes(), "parsing", || {
382 Input::File(ref file) => {
383 parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
385 Input::Str(ref src) => {
386 parse::parse_crate_from_source_str(anon_src().to_string(),
394 if sess.opts.debugging_opts.ast_json_noexpand {
395 println!("{}", json::as_json(&krate));
398 if let Some(ref s) = sess.opts.show_span {
399 syntax::show_span::run(sess.diagnostic(), s, &krate);
405 // For continuing compilation after a parsed crate has been
408 /// Run the "early phases" of the compiler: initial `cfg` processing,
409 /// loading compiler plugins (including those from `addl_plugins`),
410 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
411 /// harness if one is to be provided and injection of a dependency on the
412 /// standard library and prelude.
414 /// Returns `None` if we're aborting after handling -W help.
415 pub fn phase_2_configure_and_expand(sess: &Session,
416 mut krate: ast::Crate,
418 addl_plugins: Option<Vec<String>>)
419 -> Option<ast::Crate> {
420 let time_passes = sess.time_passes();
422 // strip before anything else because crate metadata may use #[cfg_attr]
423 // and so macros can depend on configuration variables, such as
425 // #[macro_use] #[cfg(foo)]
426 // mod bar { macro_rules! baz!(() => {{}}) }
428 // baz! should not use this definition unless foo is enabled.
430 let mut feature_gated_cfgs = vec![];
431 krate = time(time_passes, "configuration 1", ||
432 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate,
433 &mut feature_gated_cfgs));
435 *sess.crate_types.borrow_mut() =
436 collect_crate_types(sess, &krate.attrs);
437 *sess.crate_metadata.borrow_mut() =
438 collect_crate_metadata(sess, &krate.attrs);
440 time(time_passes, "recursion limit", || {
441 middle::recursion_limit::update_recursion_limit(sess, &krate);
444 time(time_passes, "gated macro checking", || {
446 syntax::feature_gate::check_crate_macros(sess.codemap(),
447 &sess.parse_sess.span_diagnostic,
450 // these need to be set "early" so that expansion sees `quote` if enabled.
451 *sess.features.borrow_mut() = features;
452 sess.abort_if_errors();
456 krate = time(time_passes, "crate injection", ||
457 syntax::std_inject::maybe_inject_crates_ref(krate,
458 sess.opts.alt_std_name.clone()));
460 let macros = time(time_passes, "macro loading", ||
461 metadata::macro_import::read_macro_defs(sess, &krate));
463 let mut addl_plugins = Some(addl_plugins);
464 let registrars = time(time_passes, "plugin loading", ||
465 plugin::load::load_plugins(sess, &krate, addl_plugins.take().unwrap()));
467 let mut registry = Registry::new(sess, &krate);
469 time(time_passes, "plugin registration", || {
470 if sess.features.borrow().rustc_diagnostic_macros {
471 registry.register_macro("__diagnostic_used",
472 diagnostics::plugin::expand_diagnostic_used);
473 registry.register_macro("__register_diagnostic",
474 diagnostics::plugin::expand_register_diagnostic);
475 registry.register_macro("__build_diagnostic_array",
476 diagnostics::plugin::expand_build_diagnostic_array);
479 for registrar in registrars {
480 registry.args_hidden = Some(registrar.args);
481 (registrar.fun)(&mut registry);
485 let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups,
486 llvm_passes, attributes, .. } = registry;
489 let mut ls = sess.lint_store.borrow_mut();
490 for pass in early_lint_passes {
491 ls.register_early_pass(Some(sess), true, pass);
493 for pass in late_lint_passes {
494 ls.register_late_pass(Some(sess), true, pass);
497 for (name, to) in lint_groups {
498 ls.register_group(Some(sess), true, name, to);
501 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
502 *sess.plugin_attributes.borrow_mut() = attributes.clone();
505 // Lint plugins are registered; now we can process command line flags.
506 if sess.opts.describe_lints {
507 super::describe_lints(&*sess.lint_store.borrow(), true);
510 sess.lint_store.borrow_mut().process_command_line(sess);
512 // Abort if there are errors from lint processing or a plugin registrar.
513 sess.abort_if_errors();
515 krate = time(time_passes, "expansion", || {
516 // Windows dlls do not have rpaths, so they don't know how to find their
517 // dependencies. It's up to us to tell the system where to find all the
518 // dependent dlls. Note that this uses cfg!(windows) as opposed to
519 // targ_cfg because syntax extensions are always loaded for the host
520 // compiler, not for the target.
521 let mut _old_path = OsString::new();
523 _old_path = env::var_os("PATH").unwrap_or(_old_path);
524 let mut new_path = sess.host_filesearch(PathKind::All)
525 .get_dylib_search_paths();
526 new_path.extend(env::split_paths(&_old_path));
527 env::set_var("PATH", &env::join_paths(new_path).unwrap());
529 let features = sess.features.borrow();
530 let cfg = syntax::ext::expand::ExpansionConfig {
531 crate_name: crate_name.to_string(),
532 features: Some(&features),
533 recursion_limit: sess.recursion_limit.get(),
534 trace_mac: sess.opts.debugging_opts.trace_macros,
536 let ret = syntax::ext::expand::expand_crate(&sess.parse_sess,
540 &mut feature_gated_cfgs,
543 env::set_var("PATH", &_old_path);
548 // Needs to go *after* expansion to be able to check the results
549 // of macro expansion. This runs before #[cfg] to try to catch as
550 // much as possible (e.g. help the programmer avoid platform
551 // specific differences)
552 time(time_passes, "complete gated feature checking 1", || {
554 syntax::feature_gate::check_crate(sess.codemap(),
555 &sess.parse_sess.span_diagnostic,
557 sess.opts.unstable_features);
558 *sess.features.borrow_mut() = features;
559 sess.abort_if_errors();
562 // JBC: make CFG processing part of expansion to avoid this problem:
564 // strip again, in case expansion added anything with a #[cfg].
565 krate = time(time_passes, "configuration 2", ||
566 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate,
567 &mut feature_gated_cfgs));
569 time(time_passes, "gated configuration checking", || {
570 let features = sess.features.borrow();
571 feature_gated_cfgs.sort();
572 feature_gated_cfgs.dedup();
573 for cfg in &feature_gated_cfgs {
574 cfg.check_and_emit(sess.diagnostic(), &features);
578 krate = time(time_passes, "maybe building test harness", ||
579 syntax::test::modify_for_testing(&sess.parse_sess,
584 krate = time(time_passes, "prelude injection", ||
585 syntax::std_inject::maybe_inject_prelude(&sess.parse_sess, krate));
587 time(time_passes, "checking that all macro invocations are gone", ||
588 syntax::ext::expand::check_for_macros(&sess.parse_sess, &krate));
590 time(time_passes, "checking for inline asm in case the target doesn't support it", ||
591 middle::check_no_asm::check_crate(sess, &krate));
593 // One final feature gating of the true AST that gets compiled
594 // later, to make sure we've got everything (e.g. configuration
595 // can insert new attributes via `cfg_attr`)
596 time(time_passes, "complete gated feature checking 2", || {
598 syntax::feature_gate::check_crate(sess.codemap(),
599 &sess.parse_sess.span_diagnostic,
601 sess.opts.unstable_features);
602 *sess.features.borrow_mut() = features;
603 sess.abort_if_errors();
609 pub fn assign_node_ids(sess: &Session,
610 krate: ast::Crate) -> ast::Crate {
611 struct NodeIdAssigner<'a> {
615 impl<'a> Folder for NodeIdAssigner<'a> {
616 fn new_id(&mut self, old_id: ast::NodeId) -> ast::NodeId {
617 assert_eq!(old_id, ast::DUMMY_NODE_ID);
618 self.sess.next_node_id()
622 let krate = time(sess.time_passes(),
623 "assigning node ids",
624 || NodeIdAssigner { sess: sess }.fold_crate(krate));
626 if sess.opts.debugging_opts.ast_json {
627 println!("{}", json::as_json(&krate));
633 pub fn make_map<'ast>(sess: &Session,
634 forest: &'ast mut front::map::Forest)
635 -> front::map::Map<'ast> {
636 // Construct the 'ast'-map
637 let map = time(sess.time_passes(),
639 move || front::map::map_crate(forest));
644 /// Run the resolution, typechecking, region checking and other
645 /// miscellaneous analysis passes on the crate. Return various
646 /// structures carrying the results of the analysis.
647 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: Session,
648 ast_map: front::map::Map<'tcx>,
649 arenas: &'tcx ty::CtxtArenas<'tcx>,
651 make_glob_map: resolve::MakeGlobMap,
654 where F: for<'a> FnOnce(&'a ty::ctxt<'tcx>,
655 ty::CrateAnalysis) -> R
657 let time_passes = sess.time_passes();
658 let krate = ast_map.krate();
660 time(time_passes, "external crate/lib resolution", ||
661 LocalCrateReader::new(&sess, &ast_map).read_crates(krate));
663 let lang_items = time(time_passes, "language item collection", ||
664 middle::lang_items::collect_language_items(krate, &sess));
666 let resolve::CrateMap {
674 time(time_passes, "resolution",
675 || resolve::resolve_crate(&sess, &ast_map, make_glob_map));
677 // Discard MTWT tables that aren't required past resolution.
678 if !sess.opts.debugging_opts.keep_mtwt_tables {
679 syntax::ext::mtwt::clear_tables();
682 let named_region_map = time(time_passes, "lifetime resolution",
683 || middle::resolve_lifetime::krate(&sess, krate, &def_map));
685 time(time_passes, "looking for entry point",
686 || middle::entry::find_entry_point(&sess, &ast_map));
688 sess.plugin_registrar_fn.set(
689 time(time_passes, "looking for plugin registrar", ||
690 plugin::build::find_plugin_registrar(
691 sess.diagnostic(), krate)));
693 let region_map = time(time_passes, "region resolution", ||
694 middle::region::resolve_crate(&sess, krate));
696 time(time_passes, "loop checking", ||
697 middle::check_loop::check_crate(&sess, krate));
699 time(time_passes, "static item recursion checking", ||
700 middle::check_static_recursion::check_crate(&sess, krate, &def_map, &ast_map));
702 ty::ctxt::create_and_enter(sess,
710 stability::Index::new(krate),
713 // passes are timed inside typeck
714 typeck::check_crate(tcx, trait_map);
716 time(time_passes, "MIR dump", ||
717 mir::dump::dump_crate(tcx));
719 time(time_passes, "const checking", ||
720 middle::check_const::check_crate(tcx));
722 let (exported_items, public_items) =
723 time(time_passes, "privacy checking", ||
724 rustc_privacy::check_crate(tcx, &export_map, external_exports));
726 // Do not move this check past lint
727 time(time_passes, "stability index", ||
728 tcx.stability.borrow_mut().build(tcx, krate, &public_items));
730 time(time_passes, "intrinsic checking", ||
731 middle::intrinsicck::check_crate(tcx));
733 time(time_passes, "effect checking", ||
734 middle::effect::check_crate(tcx));
736 time(time_passes, "match checking", ||
737 middle::check_match::check_crate(tcx));
739 time(time_passes, "liveness checking", ||
740 middle::liveness::check_crate(tcx));
742 time(time_passes, "borrow checking", ||
743 borrowck::check_crate(tcx));
745 time(time_passes, "rvalue checking", ||
746 middle::check_rvalues::check_crate(tcx, krate));
748 // Avoid overwhelming user with errors if type checking failed.
749 // I'm not sure how helpful this is, to be honest, but it avoids a
750 // lot of annoying errors in the compile-fail tests (basically,
751 // lint warnings and so on -- kindck used to do this abort, but
752 // kindck is gone now). -nmatsakis
753 tcx.sess.abort_if_errors();
756 time(time_passes, "reachability checking", ||
757 reachable::find_reachable(tcx, &exported_items));
759 time(time_passes, "death checking", || {
760 middle::dead::check_crate(tcx,
765 let ref lib_features_used =
766 time(time_passes, "stability checking", ||
767 stability::check_unstable_api_usage(tcx));
769 time(time_passes, "unused lib feature checking", ||
770 stability::check_unused_or_stable_features(
771 &tcx.sess, lib_features_used));
773 time(time_passes, "lint checking", ||
774 lint::check_crate(tcx, krate, &exported_items));
776 // The above three passes generate errors w/o aborting
777 tcx.sess.abort_if_errors();
779 f(tcx, ty::CrateAnalysis {
780 export_map: export_map,
781 exported_items: exported_items,
782 public_items: public_items,
783 reachable: reachable_map,
790 /// Run the translation phase to LLVM, after which the AST and analysis can
792 pub fn phase_4_translate_to_llvm(tcx: &ty::ctxt, analysis: ty::CrateAnalysis)
793 -> trans::CrateTranslation {
794 let time_passes = tcx.sess.time_passes();
796 time(time_passes, "resolving dependency formats", ||
797 dependency_format::calculate(&tcx.sess));
799 // Option dance to work around the lack of stack once closures.
800 time(time_passes, "translation", move ||
801 trans::trans_crate(tcx, analysis))
804 /// Run LLVM itself, producing a bitcode file, assembly file or object file
805 /// as a side effect.
806 pub fn phase_5_run_llvm_passes(sess: &Session,
807 trans: &trans::CrateTranslation,
808 outputs: &OutputFilenames) {
809 if sess.opts.cg.no_integrated_as {
810 let output_type = config::OutputTypeAssembly;
812 time(sess.time_passes(), "LLVM passes", ||
813 write::run_passes(sess, trans, &[output_type], outputs));
815 write::run_assembler(sess, outputs);
817 // Remove assembly source, unless --save-temps was specified
818 if !sess.opts.cg.save_temps {
819 fs::remove_file(&outputs.temp_path(config::OutputTypeAssembly)).unwrap();
822 time(sess.time_passes(), "LLVM passes", ||
823 write::run_passes(sess,
825 &sess.opts.output_types,
829 sess.abort_if_errors();
832 /// Run the linker on any artifacts that resulted from the LLVM run.
833 /// This should produce either a finished executable or library.
834 pub fn phase_6_link_output(sess: &Session,
835 trans: &trans::CrateTranslation,
836 outputs: &OutputFilenames) {
837 time(sess.time_passes(), "linking", ||
838 link::link_binary(sess,
841 &trans.link.crate_name));
844 fn escape_dep_filename(filename: &str) -> String {
845 // Apparently clang and gcc *only* escape spaces:
846 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
847 filename.replace(" ", "\\ ")
850 fn write_out_deps(sess: &Session,
852 outputs: &OutputFilenames,
855 let mut out_filenames = Vec::new();
856 for output_type in &sess.opts.output_types {
857 let file = outputs.path(*output_type);
859 config::OutputTypeExe => {
860 for output in sess.crate_types.borrow().iter() {
861 let p = link::filename_for_input(sess, *output, id,
863 out_filenames.push(p);
866 _ => { out_filenames.push(file); }
870 // Write out dependency rules to the dep-info file if requested with
872 let deps_filename = match sess.opts.write_dependency_info {
873 // Use filename from --dep-file argument if given
874 (true, Some(ref filename)) => filename.clone(),
875 // Use default filename: crate source filename with extension replaced
877 (true, None) => match *input {
878 Input::File(..) => outputs.with_extension("d"),
880 sess.warn("can not write --dep-info without a filename \
881 when compiling stdin.");
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 {
899 try!(write!(&mut file,
900 "{}: {}\n\n", path.display(), files.join(" ")));
908 sess.fatal(&format!("error writing dependencies to `{}`: {}",
909 deps_filename.display(), e));
914 pub fn collect_crate_types(session: &Session,
915 attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
916 // Unconditionally collect crate types from attributes to make them used
917 let attr_types: Vec<config::CrateType> = attrs.iter().filter_map(|a| {
918 if a.check_name("crate_type") {
919 match a.value_str() {
920 Some(ref n) if *n == "rlib" => {
921 Some(config::CrateTypeRlib)
923 Some(ref n) if *n == "dylib" => {
924 Some(config::CrateTypeDylib)
926 Some(ref n) if *n == "lib" => {
927 Some(config::default_lib_output())
929 Some(ref n) if *n == "staticlib" => {
930 Some(config::CrateTypeStaticlib)
932 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
934 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
937 "invalid `crate_type` \
942 session.span_err(a.span, "`crate_type` requires a value");
943 session.note("for example: `#![crate_type=\"lib\"]`");
952 // If we're generating a test executable, then ignore all other output
953 // styles at all other locations
954 if session.opts.test {
955 return vec!(config::CrateTypeExecutable)
958 // Only check command line flags if present. If no types are specified by
959 // command line, then reuse the empty `base` Vec to hold the types that
960 // will be found in crate attributes.
961 let mut base = session.opts.crate_types.clone();
963 base.extend(attr_types);
965 base.push(link::default_output_for_target(session));
971 base.into_iter().filter(|crate_type| {
972 let res = !link::invalid_output_for_target(session, *crate_type);
975 session.warn(&format!("dropping unsupported crate type `{}` \
977 *crate_type, session.opts.target_triple));
984 pub fn collect_crate_metadata(session: &Session,
985 _attrs: &[ast::Attribute]) -> Vec<String> {
986 session.opts.cg.metadata.clone()
989 pub fn build_output_filenames(input: &Input,
990 odir: &Option<PathBuf>,
991 ofile: &Option<PathBuf>,
992 attrs: &[ast::Attribute],
997 // "-" as input file will cause the parser to read from stdin so we
998 // have to make up a name
999 // We want to toss everything after the final '.'
1000 let dirpath = match *odir {
1001 Some(ref d) => d.clone(),
1002 None => PathBuf::new()
1005 // If a crate name is present, we use it as the link name
1006 let stem = sess.opts.crate_name.clone().or_else(|| {
1007 attr::find_crate_name(attrs).map(|n| n.to_string())
1008 }).unwrap_or(input.filestem());
1011 out_directory: dirpath,
1013 single_output_file: None,
1014 extra: sess.opts.cg.extra_filename.clone(),
1018 Some(ref out_file) => {
1019 let ofile = if sess.opts.output_types.len() > 1 {
1020 sess.warn("ignoring specified output filename because multiple \
1021 outputs were requested");
1024 Some(out_file.clone())
1027 sess.warn("ignoring --out-dir flag due to -o flag.");
1030 let cur_dir = Path::new("");
1033 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
1034 out_filestem: out_file.file_stem().unwrap_or(OsStr::new(""))
1035 .to_str().unwrap().to_string(),
1036 single_output_file: ofile,
1037 extra: sess.opts.cg.extra_filename.clone(),