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 use rustc::session::Session;
12 use rustc::session::config::{self, Input, OutputFilenames};
13 use rustc::session::search_paths::PathKind;
17 use rustc::metadata::creader::CrateReader;
18 use rustc::middle::{stability, ty, reachable};
19 use rustc::middle::dependency_format;
21 use rustc::plugin::registry::Registry;
23 use rustc::util::common::time;
24 use rustc_borrowck as borrowck;
25 use rustc_resolve as resolve;
26 use rustc_trans::back::link;
27 use rustc_trans::back::write;
28 use rustc_trans::trans;
29 use rustc_typeck as typeck;
31 use super::Compilation;
36 use std::ffi::{OsString, OsStr};
38 use std::io::{self, Write};
39 use std::path::{Path, PathBuf};
42 use syntax::attr::AttrMetaMethods;
43 use syntax::diagnostics;
45 use syntax::parse::token;
48 pub fn compile_input(sess: Session,
49 cfg: ast::CrateConfig,
51 outdir: &Option<PathBuf>,
52 output: &Option<PathBuf>,
53 addl_plugins: Option<Vec<String>>,
54 control: CompileController) {
55 macro_rules! controller_entry_point{($point: ident, $tsess: expr, $make_state: expr) => ({
56 let state = $make_state;
57 (control.$point.callback)(state);
59 $tsess.abort_if_errors();
60 if control.$point.stop == Compilation::Stop {
65 // We need nested scopes here, because the intermediate results can keep
66 // large chunks of memory alive and we want to free them as soon as
67 // possible to keep the peak memory usage low
68 let (sess, result) = {
69 let (outputs, expanded_crate, id) = {
70 let krate = phase_1_parse_input(&sess, cfg, input);
72 controller_entry_point!(after_parse,
74 CompileState::state_after_parse(input,
79 let outputs = build_output_filenames(input,
84 let id = link::find_crate_name(Some(&sess),
88 = match phase_2_configure_and_expand(&sess,
96 (outputs, expanded_crate, id)
99 controller_entry_point!(after_expand,
101 CompileState::state_after_expand(input,
107 let mut forest = ast_map::Forest::new(expanded_crate);
108 let arenas = ty::CtxtArenas::new();
109 let ast_map = assign_node_ids_and_map(&sess, &mut forest);
111 write_out_deps(&sess, input, &outputs, &id[..]);
113 controller_entry_point!(after_write_deps,
115 CompileState::state_after_write_deps(input,
122 phase_3_run_analysis_passes(sess,
126 control.make_glob_map,
130 let state = CompileState::state_after_analysis(input,
136 (control.after_analysis.callback)(state);
138 tcx.sess.abort_if_errors();
139 if control.after_analysis.stop == Compilation::Stop {
144 if log_enabled!(::log::INFO) {
145 println!("Pre-trans");
146 tcx.print_debug_stats();
148 let trans = phase_4_translate_to_llvm(tcx, analysis);
150 if log_enabled!(::log::INFO) {
151 println!("Post-trans");
152 tcx.print_debug_stats();
155 // Discard interned strings as they are no longer required.
156 token::get_ident_interner().clear();
162 let (outputs, trans) = if let Ok(out) = result {
168 phase_5_run_llvm_passes(&sess, &trans, &outputs);
170 controller_entry_point!(after_llvm,
172 CompileState::state_after_llvm(input,
177 phase_6_link_output(&sess, &trans, &outputs);
180 /// The name used for source code that doesn't originate in a file
181 /// (e.g. source from stdin or a string)
182 pub fn anon_src() -> String {
186 pub fn source_name(input: &Input) -> String {
188 // FIXME (#9639): This needs to handle non-utf8 paths
189 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
190 Input::Str(_) => anon_src()
194 /// CompileController is used to customise compilation, it allows compilation to
195 /// be stopped and/or to call arbitrary code at various points in compilation.
196 /// It also allows for various flags to be set to influence what information gets
197 /// collected during compilation.
199 /// This is a somewhat higher level controller than a Session - the Session
200 /// controls what happens in each phase, whereas the CompileController controls
201 /// whether a phase is run at all and whether other code (from outside the
202 /// the compiler) is run between phases.
204 /// Note that if compilation is set to stop and a callback is provided for a
205 /// given entry point, the callback is called before compilation is stopped.
207 /// Expect more entry points to be added in the future.
208 pub struct CompileController<'a> {
209 pub after_parse: PhaseController<'a>,
210 pub after_expand: PhaseController<'a>,
211 pub after_write_deps: PhaseController<'a>,
212 pub after_analysis: PhaseController<'a>,
213 pub after_llvm: PhaseController<'a>,
215 pub make_glob_map: resolve::MakeGlobMap,
218 impl<'a> CompileController<'a> {
219 pub fn basic() -> CompileController<'a> {
221 after_parse: PhaseController::basic(),
222 after_expand: PhaseController::basic(),
223 after_write_deps: PhaseController::basic(),
224 after_analysis: PhaseController::basic(),
225 after_llvm: PhaseController::basic(),
226 make_glob_map: resolve::MakeGlobMap::No,
231 pub struct PhaseController<'a> {
232 pub stop: Compilation,
233 pub callback: Box<Fn(CompileState) -> () + 'a>,
236 impl<'a> PhaseController<'a> {
237 pub fn basic() -> PhaseController<'a> {
239 stop: Compilation::Continue,
240 callback: box |_| {},
245 /// State that is passed to a callback. What state is available depends on when
246 /// during compilation the callback is made. See the various constructor methods
247 /// (`state_*`) in the impl to see which data is provided for any given entry point.
248 pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
249 pub input: &'a Input,
250 pub session: &'a Session,
251 pub cfg: Option<&'a ast::CrateConfig>,
252 pub krate: Option<&'a ast::Crate>,
253 pub crate_name: Option<&'a str>,
254 pub output_filenames: Option<&'a OutputFilenames>,
255 pub out_dir: Option<&'a Path>,
256 pub expanded_crate: Option<&'a ast::Crate>,
257 pub ast_map: Option<&'a ast_map::Map<'ast>>,
258 pub analysis: Option<&'a ty::CrateAnalysis>,
259 pub tcx: Option<&'a ty::ctxt<'tcx>>,
260 pub trans: Option<&'a trans::CrateTranslation>,
263 impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
264 fn empty(input: &'a Input,
265 session: &'a Session,
266 out_dir: &'a Option<PathBuf>)
267 -> CompileState<'a, 'ast, 'tcx> {
271 out_dir: out_dir.as_ref().map(|s| &**s),
275 output_filenames: None,
276 expanded_crate: None,
284 fn state_after_parse(input: &'a Input,
285 session: &'a Session,
286 out_dir: &'a Option<PathBuf>,
287 krate: &'a ast::Crate)
288 -> CompileState<'a, 'ast, 'tcx> {
291 .. CompileState::empty(input, session, out_dir)
295 fn state_after_expand(input: &'a Input,
296 session: &'a Session,
297 out_dir: &'a Option<PathBuf>,
298 expanded_crate: &'a ast::Crate,
300 -> CompileState<'a, 'ast, 'tcx> {
302 crate_name: Some(crate_name),
303 expanded_crate: Some(expanded_crate),
304 .. CompileState::empty(input, session, out_dir)
308 fn state_after_write_deps(input: &'a Input,
309 session: &'a Session,
310 out_dir: &'a Option<PathBuf>,
311 ast_map: &'a ast_map::Map<'ast>,
312 expanded_crate: &'a ast::Crate,
314 -> CompileState<'a, 'ast, 'tcx> {
316 crate_name: Some(crate_name),
317 ast_map: Some(ast_map),
318 expanded_crate: Some(expanded_crate),
319 .. CompileState::empty(input, session, out_dir)
323 fn state_after_analysis(input: &'a Input,
324 session: &'a Session,
325 out_dir: &'a Option<PathBuf>,
326 expanded_crate: &'a ast::Crate,
327 analysis: &'a ty::CrateAnalysis,
328 tcx: &'a ty::ctxt<'tcx>)
329 -> CompileState<'a, 'ast, 'tcx> {
331 analysis: Some(analysis),
333 expanded_crate: Some(expanded_crate),
334 .. CompileState::empty(input, session, out_dir)
339 fn state_after_llvm(input: &'a Input,
340 session: &'a Session,
341 out_dir: &'a Option<PathBuf>,
342 trans: &'a trans::CrateTranslation)
343 -> CompileState<'a, 'ast, 'tcx> {
346 .. CompileState::empty(input, session, out_dir)
351 pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
353 // These may be left in an incoherent state after a previous compile.
354 // `clear_tables` and `get_ident_interner().clear()` can be used to free
355 // memory, but they do not restore the initial state.
356 syntax::ext::mtwt::reset_tables();
357 token::reset_ident_interner();
359 let krate = time(sess.time_passes(), "parsing", (), |_| {
361 Input::File(ref file) => {
362 parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
364 Input::Str(ref src) => {
365 parse::parse_crate_from_source_str(anon_src().to_string(),
373 if sess.opts.debugging_opts.ast_json_noexpand {
374 println!("{}", json::as_json(&krate));
377 if let Some(ref s) = sess.opts.show_span {
378 syntax::show_span::run(sess.diagnostic(), s, &krate);
384 // For continuing compilation after a parsed crate has been
387 /// Run the "early phases" of the compiler: initial `cfg` processing,
388 /// loading compiler plugins (including those from `addl_plugins`),
389 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
390 /// harness if one is to be provided and injection of a dependency on the
391 /// standard library and prelude.
393 /// Returns `None` if we're aborting after handling -W help.
394 pub fn phase_2_configure_and_expand(sess: &Session,
395 mut krate: ast::Crate,
397 addl_plugins: Option<Vec<String>>)
398 -> Option<ast::Crate> {
399 let time_passes = sess.time_passes();
401 // strip before anything else because crate metadata may use #[cfg_attr]
402 // and so macros can depend on configuration variables, such as
404 // #[macro_use] #[cfg(foo)]
405 // mod bar { macro_rules! baz!(() => {{}}) }
407 // baz! should not use this definition unless foo is enabled.
409 krate = time(time_passes, "configuration 1", krate, |krate|
410 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate));
412 *sess.crate_types.borrow_mut() =
413 collect_crate_types(sess, &krate.attrs);
414 *sess.crate_metadata.borrow_mut() =
415 collect_crate_metadata(sess, &krate.attrs);
417 time(time_passes, "recursion limit", (), |_| {
418 middle::recursion_limit::update_recursion_limit(sess, &krate);
421 time(time_passes, "gated macro checking", (), |_| {
423 syntax::feature_gate::check_crate_macros(sess.codemap(),
424 &sess.parse_sess.span_diagnostic,
427 // these need to be set "early" so that expansion sees `quote` if enabled.
428 *sess.features.borrow_mut() = features;
429 sess.abort_if_errors();
433 krate = time(time_passes, "crate injection", krate, |krate|
434 syntax::std_inject::maybe_inject_crates_ref(krate,
435 sess.opts.alt_std_name.clone()));
437 let macros = time(time_passes, "macro loading", (), |_|
438 metadata::macro_import::read_macro_defs(sess, &krate));
440 let mut addl_plugins = Some(addl_plugins);
441 let registrars = time(time_passes, "plugin loading", (), |_|
442 plugin::load::load_plugins(sess, &krate, addl_plugins.take().unwrap()));
444 let mut registry = Registry::new(sess, &krate);
446 time(time_passes, "plugin registration", registrars, |registrars| {
447 if sess.features.borrow().rustc_diagnostic_macros {
448 registry.register_macro("__diagnostic_used",
449 diagnostics::plugin::expand_diagnostic_used);
450 registry.register_macro("__register_diagnostic",
451 diagnostics::plugin::expand_register_diagnostic);
452 registry.register_macro("__build_diagnostic_array",
453 diagnostics::plugin::expand_build_diagnostic_array);
456 for registrar in registrars {
457 registry.args_hidden = Some(registrar.args);
458 (registrar.fun)(&mut registry);
462 let Registry { syntax_exts, lint_passes, lint_groups,
463 llvm_passes, attributes, .. } = registry;
466 let mut ls = sess.lint_store.borrow_mut();
467 for pass in lint_passes {
468 ls.register_pass(Some(sess), true, pass);
471 for (name, to) in lint_groups {
472 ls.register_group(Some(sess), true, name, to);
475 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
476 *sess.plugin_attributes.borrow_mut() = attributes.clone();
479 // Lint plugins are registered; now we can process command line flags.
480 if sess.opts.describe_lints {
481 super::describe_lints(&*sess.lint_store.borrow(), true);
484 sess.lint_store.borrow_mut().process_command_line(sess);
486 // Abort if there are errors from lint processing or a plugin registrar.
487 sess.abort_if_errors();
489 krate = time(time_passes, "expansion", (krate, macros, syntax_exts),
490 |(krate, macros, syntax_exts)| {
491 // Windows dlls do not have rpaths, so they don't know how to find their
492 // dependencies. It's up to us to tell the system where to find all the
493 // dependent dlls. Note that this uses cfg!(windows) as opposed to
494 // targ_cfg because syntax extensions are always loaded for the host
495 // compiler, not for the target.
496 let mut _old_path = OsString::new();
498 _old_path = env::var_os("PATH").unwrap_or(_old_path);
499 let mut new_path = sess.host_filesearch(PathKind::All)
500 .get_dylib_search_paths();
501 new_path.extend(env::split_paths(&_old_path));
502 env::set_var("PATH", &env::join_paths(new_path).unwrap());
504 let features = sess.features.borrow();
505 let cfg = syntax::ext::expand::ExpansionConfig {
506 crate_name: crate_name.to_string(),
507 features: Some(&features),
508 recursion_limit: sess.recursion_limit.get(),
509 trace_mac: sess.opts.debugging_opts.trace_macros,
511 let ret = syntax::ext::expand::expand_crate(&sess.parse_sess,
517 env::set_var("PATH", &_old_path);
523 // Needs to go *after* expansion to be able to check the results
524 // of macro expansion. This runs before #[cfg] to try to catch as
525 // much as possible (e.g. help the programmer avoid platform
526 // specific differences)
527 time(time_passes, "complete gated feature checking 1", (), |_| {
529 syntax::feature_gate::check_crate(sess.codemap(),
530 &sess.parse_sess.span_diagnostic,
532 sess.opts.unstable_features);
533 *sess.features.borrow_mut() = features;
534 sess.abort_if_errors();
537 // JBC: make CFG processing part of expansion to avoid this problem:
539 // strip again, in case expansion added anything with a #[cfg].
540 krate = time(time_passes, "configuration 2", krate, |krate|
541 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate));
543 krate = time(time_passes, "maybe building test harness", krate, |krate|
544 syntax::test::modify_for_testing(&sess.parse_sess,
549 krate = time(time_passes, "prelude injection", krate, |krate|
550 syntax::std_inject::maybe_inject_prelude(&sess.parse_sess, krate));
552 time(time_passes, "checking that all macro invocations are gone", &krate, |krate|
553 syntax::ext::expand::check_for_macros(&sess.parse_sess, krate));
555 // One final feature gating of the true AST that gets compiled
556 // later, to make sure we've got everything (e.g. configuration
557 // can insert new attributes via `cfg_attr`)
558 time(time_passes, "complete gated feature checking 2", (), |_| {
560 syntax::feature_gate::check_crate(sess.codemap(),
561 &sess.parse_sess.span_diagnostic,
563 sess.opts.unstable_features);
564 *sess.features.borrow_mut() = features;
565 sess.abort_if_errors();
571 pub fn assign_node_ids_and_map<'ast>(sess: &Session,
572 forest: &'ast mut ast_map::Forest)
573 -> ast_map::Map<'ast> {
574 struct NodeIdAssigner<'a> {
578 impl<'a> ast_map::FoldOps for NodeIdAssigner<'a> {
579 fn new_id(&self, old_id: ast::NodeId) -> ast::NodeId {
580 assert_eq!(old_id, ast::DUMMY_NODE_ID);
581 self.sess.next_node_id()
585 let map = time(sess.time_passes(), "assigning node ids and indexing ast", forest, |forest|
586 ast_map::map_crate(forest, NodeIdAssigner { sess: sess }));
588 if sess.opts.debugging_opts.ast_json {
589 println!("{}", json::as_json(map.krate()));
595 /// Run the resolution, typechecking, region checking and other
596 /// miscellaneous analysis passes on the crate. Return various
597 /// structures carrying the results of the analysis.
598 pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: Session,
599 ast_map: ast_map::Map<'tcx>,
600 arenas: &'tcx ty::CtxtArenas<'tcx>,
602 make_glob_map: resolve::MakeGlobMap,
605 where F: for<'a> FnOnce(&'a ty::ctxt<'tcx>,
606 ty::CrateAnalysis) -> R
608 let time_passes = sess.time_passes();
609 let krate = ast_map.krate();
611 time(time_passes, "external crate/lib resolution", (), |_|
612 CrateReader::new(&sess).read_crates(krate));
614 let lang_items = time(time_passes, "language item collection", (), |_|
615 middle::lang_items::collect_language_items(krate, &sess));
617 let resolve::CrateMap {
625 time(time_passes, "resolution", (),
626 |_| resolve::resolve_crate(&sess, &ast_map, make_glob_map));
628 // Discard MTWT tables that aren't required past resolution.
629 syntax::ext::mtwt::clear_tables();
631 let named_region_map = time(time_passes, "lifetime resolution", (),
632 |_| middle::resolve_lifetime::krate(&sess, krate, &def_map));
634 time(time_passes, "looking for entry point", (),
635 |_| middle::entry::find_entry_point(&sess, &ast_map));
637 sess.plugin_registrar_fn.set(
638 time(time_passes, "looking for plugin registrar", (), |_|
639 plugin::build::find_plugin_registrar(
640 sess.diagnostic(), krate)));
642 let region_map = time(time_passes, "region resolution", (), |_|
643 middle::region::resolve_crate(&sess, krate));
645 time(time_passes, "loop checking", (), |_|
646 middle::check_loop::check_crate(&sess, krate));
648 time(time_passes, "static item recursion checking", (), |_|
649 middle::check_static_recursion::check_crate(&sess, krate, &def_map, &ast_map));
651 ty::ctxt::create_and_enter(sess,
659 stability::Index::new(krate),
662 // passes are timed inside typeck
663 typeck::check_crate(tcx, trait_map);
665 time(time_passes, "const checking", (), |_|
666 middle::check_const::check_crate(tcx));
668 let (exported_items, public_items) =
669 time(time_passes, "privacy checking", (), |_|
670 rustc_privacy::check_crate(tcx, &export_map, external_exports));
672 // Do not move this check past lint
673 time(time_passes, "stability index", (), |_|
674 tcx.stability.borrow_mut().build(tcx, krate, &public_items));
676 time(time_passes, "intrinsic checking", (), |_|
677 middle::intrinsicck::check_crate(tcx));
679 time(time_passes, "effect checking", (), |_|
680 middle::effect::check_crate(tcx));
682 time(time_passes, "match checking", (), |_|
683 middle::check_match::check_crate(tcx));
685 time(time_passes, "liveness checking", (), |_|
686 middle::liveness::check_crate(tcx));
688 time(time_passes, "borrow checking", (), |_|
689 borrowck::check_crate(tcx));
691 time(time_passes, "rvalue checking", (), |_|
692 middle::check_rvalues::check_crate(tcx, krate));
694 // Avoid overwhelming user with errors if type checking failed.
695 // I'm not sure how helpful this is, to be honest, but it avoids a
696 // lot of annoying errors in the compile-fail tests (basically,
697 // lint warnings and so on -- kindck used to do this abort, but
698 // kindck is gone now). -nmatsakis
699 tcx.sess.abort_if_errors();
702 time(time_passes, "reachability checking", (), |_|
703 reachable::find_reachable(tcx, &exported_items));
705 time(time_passes, "death checking", (), |_| {
706 middle::dead::check_crate(tcx,
711 let ref lib_features_used =
712 time(time_passes, "stability checking", (), |_|
713 stability::check_unstable_api_usage(tcx));
715 time(time_passes, "unused lib feature checking", (), |_|
716 stability::check_unused_or_stable_features(
717 &tcx.sess, lib_features_used));
719 time(time_passes, "lint checking", (), |_|
720 lint::check_crate(tcx, &exported_items));
722 // The above three passes generate errors w/o aborting
723 tcx.sess.abort_if_errors();
725 f(tcx, ty::CrateAnalysis {
726 export_map: export_map,
727 exported_items: exported_items,
728 public_items: public_items,
729 reachable: reachable_map,
736 /// Run the translation phase to LLVM, after which the AST and analysis can
738 pub fn phase_4_translate_to_llvm(tcx: &ty::ctxt, analysis: ty::CrateAnalysis)
739 -> trans::CrateTranslation {
740 let time_passes = tcx.sess.time_passes();
742 time(time_passes, "resolving dependency formats", (), |_|
743 dependency_format::calculate(tcx));
745 // Option dance to work around the lack of stack once closures.
746 time(time_passes, "translation", analysis, |analysis|
747 trans::trans_crate(tcx, analysis))
750 /// Run LLVM itself, producing a bitcode file, assembly file or object file
751 /// as a side effect.
752 pub fn phase_5_run_llvm_passes(sess: &Session,
753 trans: &trans::CrateTranslation,
754 outputs: &OutputFilenames) {
755 if sess.opts.cg.no_integrated_as {
756 let output_type = config::OutputTypeAssembly;
758 time(sess.time_passes(), "LLVM passes", (), |_|
759 write::run_passes(sess, trans, &[output_type], outputs));
761 write::run_assembler(sess, outputs);
763 // Remove assembly source, unless --save-temps was specified
764 if !sess.opts.cg.save_temps {
765 fs::remove_file(&outputs.temp_path(config::OutputTypeAssembly)).unwrap();
768 time(sess.time_passes(), "LLVM passes", (), |_|
769 write::run_passes(sess,
771 &sess.opts.output_types,
775 sess.abort_if_errors();
778 /// Run the linker on any artifacts that resulted from the LLVM run.
779 /// This should produce either a finished executable or library.
780 pub fn phase_6_link_output(sess: &Session,
781 trans: &trans::CrateTranslation,
782 outputs: &OutputFilenames) {
783 time(sess.time_passes(), "linking", (), |_|
784 link::link_binary(sess,
787 &trans.link.crate_name));
790 fn escape_dep_filename(filename: &str) -> String {
791 // Apparently clang and gcc *only* escape spaces:
792 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
793 filename.replace(" ", "\\ ")
796 fn write_out_deps(sess: &Session,
798 outputs: &OutputFilenames,
801 let mut out_filenames = Vec::new();
802 for output_type in &sess.opts.output_types {
803 let file = outputs.path(*output_type);
805 config::OutputTypeExe => {
806 for output in sess.crate_types.borrow().iter() {
807 let p = link::filename_for_input(sess, *output, id,
809 out_filenames.push(p);
812 _ => { out_filenames.push(file); }
816 // Write out dependency rules to the dep-info file if requested with
818 let deps_filename = match sess.opts.write_dependency_info {
819 // Use filename from --dep-file argument if given
820 (true, Some(ref filename)) => filename.clone(),
821 // Use default filename: crate source filename with extension replaced
823 (true, None) => match *input {
824 Input::File(..) => outputs.with_extension("d"),
826 sess.warn("can not write --dep-info without a filename \
827 when compiling stdin.");
834 let result = (|| -> io::Result<()> {
835 // Build a list of files used to compile the output and
836 // write Makefile-compatible dependency rules
837 let files: Vec<String> = sess.codemap().files.borrow()
839 .filter(|fmap| fmap.is_real_file())
840 .filter(|fmap| !fmap.is_imported())
841 .map(|fmap| escape_dep_filename(&fmap.name))
843 let mut file = try!(fs::File::create(&deps_filename));
844 for path in &out_filenames {
845 try!(write!(&mut file,
846 "{}: {}\n\n", path.display(), files.join(" ")));
854 sess.fatal(&format!("error writing dependencies to `{}`: {}",
855 deps_filename.display(), e));
860 pub fn collect_crate_types(session: &Session,
861 attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
862 // Unconditionally collect crate types from attributes to make them used
863 let attr_types: Vec<config::CrateType> = attrs.iter().filter_map(|a| {
864 if a.check_name("crate_type") {
865 match a.value_str() {
866 Some(ref n) if *n == "rlib" => {
867 Some(config::CrateTypeRlib)
869 Some(ref n) if *n == "dylib" => {
870 Some(config::CrateTypeDylib)
872 Some(ref n) if *n == "lib" => {
873 Some(config::default_lib_output())
875 Some(ref n) if *n == "staticlib" => {
876 Some(config::CrateTypeStaticlib)
878 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
880 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
883 "invalid `crate_type` \
888 session.span_err(a.span, "`crate_type` requires a value");
889 session.note("for example: `#![crate_type=\"lib\"]`");
898 // If we're generating a test executable, then ignore all other output
899 // styles at all other locations
900 if session.opts.test {
901 return vec!(config::CrateTypeExecutable)
904 // Only check command line flags if present. If no types are specified by
905 // command line, then reuse the empty `base` Vec to hold the types that
906 // will be found in crate attributes.
907 let mut base = session.opts.crate_types.clone();
909 base.extend(attr_types);
911 base.push(link::default_output_for_target(session));
917 base.into_iter().filter(|crate_type| {
918 let res = !link::invalid_output_for_target(session, *crate_type);
921 session.warn(&format!("dropping unsupported crate type `{}` \
923 *crate_type, session.opts.target_triple));
930 pub fn collect_crate_metadata(session: &Session,
931 _attrs: &[ast::Attribute]) -> Vec<String> {
932 session.opts.cg.metadata.clone()
935 pub fn build_output_filenames(input: &Input,
936 odir: &Option<PathBuf>,
937 ofile: &Option<PathBuf>,
938 attrs: &[ast::Attribute],
943 // "-" as input file will cause the parser to read from stdin so we
944 // have to make up a name
945 // We want to toss everything after the final '.'
946 let dirpath = match *odir {
947 Some(ref d) => d.clone(),
948 None => PathBuf::new()
951 // If a crate name is present, we use it as the link name
952 let stem = sess.opts.crate_name.clone().or_else(|| {
953 attr::find_crate_name(attrs).map(|n| n.to_string())
954 }).unwrap_or(input.filestem());
957 out_directory: dirpath,
959 single_output_file: None,
960 extra: sess.opts.cg.extra_filename.clone(),
964 Some(ref out_file) => {
965 let ofile = if sess.opts.output_types.len() > 1 {
966 sess.warn("ignoring specified output filename because multiple \
967 outputs were requested");
970 Some(out_file.clone())
973 sess.warn("ignoring --out-dir flag due to -o flag.");
976 let cur_dir = Path::new("");
979 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
980 out_filestem: out_file.file_stem().unwrap_or(OsStr::new(""))
981 .to_str().unwrap().to_string(),
982 single_output_file: ofile,
983 extra: sess.opts.cg.extra_filename.clone(),