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;
16 use rustc::metadata::creader::CrateReader;
17 use rustc::middle::{stability, ty, reachable};
18 use rustc::middle::dependency_format;
20 use rustc::plugin::registry::Registry;
22 use rustc::util::common::time;
23 use rustc_borrowck as borrowck;
24 use rustc_resolve as resolve;
25 use rustc_trans::back::link;
26 use rustc_trans::back::write;
27 use rustc_trans::trans;
28 use rustc_typeck as typeck;
30 use super::Compilation;
35 use std::ffi::OsString;
37 use std::io::{self, Write};
38 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 (outputs, trans, sess) = {
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 let analysis = phase_3_run_analysis_passes(sess,
126 control.make_glob_map);
128 controller_entry_point!(after_analysis,
130 CompileState::state_after_analysis(input,
131 &analysis.ty_cx.sess,
133 analysis.ty_cx.map.krate(),
137 if log_enabled!(::log::INFO) {
138 println!("Pre-trans");
139 analysis.ty_cx.print_debug_stats();
141 let (tcx, trans) = phase_4_translate_to_llvm(analysis);
143 if log_enabled!(::log::INFO) {
144 println!("Post-trans");
145 tcx.print_debug_stats();
148 // Discard interned strings as they are no longer required.
149 token::get_ident_interner().clear();
151 (outputs, trans, tcx.sess)
153 phase_5_run_llvm_passes(&sess, &trans, &outputs);
155 controller_entry_point!(after_llvm,
157 CompileState::state_after_llvm(input,
162 phase_6_link_output(&sess, &trans, &outputs);
165 /// The name used for source code that doesn't originate in a file
166 /// (e.g. source from stdin or a string)
167 pub fn anon_src() -> String {
171 pub fn source_name(input: &Input) -> String {
173 // FIXME (#9639): This needs to handle non-utf8 paths
174 Input::File(ref ifile) => ifile.to_str().unwrap().to_string(),
175 Input::Str(_) => anon_src()
179 /// CompileController is used to customise compilation, it allows compilation to
180 /// be stopped and/or to call arbitrary code at various points in compilation.
181 /// It also allows for various flags to be set to influence what information gets
182 /// collected during compilation.
184 /// This is a somewhat higher level controller than a Session - the Session
185 /// controls what happens in each phase, whereas the CompileController controls
186 /// whether a phase is run at all and whether other code (from outside the
187 /// the compiler) is run between phases.
189 /// Note that if compilation is set to stop and a callback is provided for a
190 /// given entry point, the callback is called before compilation is stopped.
192 /// Expect more entry points to be added in the future.
193 pub struct CompileController<'a> {
194 pub after_parse: PhaseController<'a>,
195 pub after_expand: PhaseController<'a>,
196 pub after_write_deps: PhaseController<'a>,
197 pub after_analysis: PhaseController<'a>,
198 pub after_llvm: PhaseController<'a>,
200 pub make_glob_map: resolve::MakeGlobMap,
203 impl<'a> CompileController<'a> {
204 pub fn basic() -> CompileController<'a> {
206 after_parse: PhaseController::basic(),
207 after_expand: PhaseController::basic(),
208 after_write_deps: PhaseController::basic(),
209 after_analysis: PhaseController::basic(),
210 after_llvm: PhaseController::basic(),
211 make_glob_map: resolve::MakeGlobMap::No,
216 pub struct PhaseController<'a> {
217 pub stop: Compilation,
218 pub callback: Box<Fn(CompileState) -> () + 'a>,
221 impl<'a> PhaseController<'a> {
222 pub fn basic() -> PhaseController<'a> {
224 stop: Compilation::Continue,
225 callback: box |_| {},
230 /// State that is passed to a callback. What state is available depends on when
231 /// during compilation the callback is made. See the various constructor methods
232 /// (`state_*`) in the impl to see which data is provided for any given entry point.
233 pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
234 pub input: &'a Input,
235 pub session: &'a Session,
236 pub cfg: Option<&'a ast::CrateConfig>,
237 pub krate: Option<&'a ast::Crate>,
238 pub crate_name: Option<&'a str>,
239 pub output_filenames: Option<&'a OutputFilenames>,
240 pub out_dir: Option<&'a Path>,
241 pub expanded_crate: Option<&'a ast::Crate>,
242 pub ast_map: Option<&'a ast_map::Map<'ast>>,
243 pub analysis: Option<&'a ty::CrateAnalysis<'tcx>>,
244 pub tcx: Option<&'a ty::ctxt<'tcx>>,
245 pub trans: Option<&'a trans::CrateTranslation>,
248 impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
249 fn empty(input: &'a Input,
250 session: &'a Session,
251 out_dir: &'a Option<PathBuf>)
252 -> CompileState<'a, 'ast, 'tcx> {
256 out_dir: out_dir.as_ref().map(|s| &**s),
260 output_filenames: None,
261 expanded_crate: None,
269 fn state_after_parse(input: &'a Input,
270 session: &'a Session,
271 out_dir: &'a Option<PathBuf>,
272 krate: &'a ast::Crate)
273 -> CompileState<'a, 'ast, 'tcx> {
276 .. CompileState::empty(input, session, out_dir)
280 fn state_after_expand(input: &'a Input,
281 session: &'a Session,
282 out_dir: &'a Option<PathBuf>,
283 expanded_crate: &'a ast::Crate,
285 -> CompileState<'a, 'ast, 'tcx> {
287 crate_name: Some(crate_name),
288 expanded_crate: Some(expanded_crate),
289 .. CompileState::empty(input, session, out_dir)
293 fn state_after_write_deps(input: &'a Input,
294 session: &'a Session,
295 out_dir: &'a Option<PathBuf>,
296 ast_map: &'a ast_map::Map<'ast>,
297 expanded_crate: &'a ast::Crate,
299 -> CompileState<'a, 'ast, 'tcx> {
301 crate_name: Some(crate_name),
302 ast_map: Some(ast_map),
303 expanded_crate: Some(expanded_crate),
304 .. CompileState::empty(input, session, out_dir)
308 fn state_after_analysis(input: &'a Input,
309 session: &'a Session,
310 out_dir: &'a Option<PathBuf>,
311 expanded_crate: &'a ast::Crate,
312 analysis: &'a ty::CrateAnalysis<'tcx>,
313 tcx: &'a ty::ctxt<'tcx>)
314 -> CompileState<'a, 'ast, 'tcx> {
316 analysis: Some(analysis),
318 expanded_crate: Some(expanded_crate),
319 .. CompileState::empty(input, session, out_dir)
324 fn state_after_llvm(input: &'a Input,
325 session: &'a Session,
326 out_dir: &'a Option<PathBuf>,
327 trans: &'a trans::CrateTranslation)
328 -> CompileState<'a, 'ast, 'tcx> {
331 .. CompileState::empty(input, session, out_dir)
336 pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
338 // These may be left in an incoherent state after a previous compile.
339 // `clear_tables` and `get_ident_interner().clear()` can be used to free
340 // memory, but they do not restore the initial state.
341 syntax::ext::mtwt::reset_tables();
342 token::reset_ident_interner();
344 let krate = time(sess.time_passes(), "parsing", (), |_| {
346 Input::File(ref file) => {
347 parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
349 Input::Str(ref src) => {
350 parse::parse_crate_from_source_str(anon_src().to_string(),
358 if sess.opts.debugging_opts.ast_json_noexpand {
359 println!("{}", json::as_json(&krate));
362 if let Some(ref s) = sess.opts.show_span {
363 syntax::show_span::run(sess.diagnostic(), s, &krate);
369 // For continuing compilation after a parsed crate has been
372 /// Run the "early phases" of the compiler: initial `cfg` processing,
373 /// loading compiler plugins (including those from `addl_plugins`),
374 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
375 /// harness if one is to be provided and injection of a dependency on the
376 /// standard library and prelude.
378 /// Returns `None` if we're aborting after handling -W help.
379 pub fn phase_2_configure_and_expand(sess: &Session,
380 mut krate: ast::Crate,
382 addl_plugins: Option<Vec<String>>)
383 -> Option<ast::Crate> {
384 let time_passes = sess.time_passes();
386 *sess.crate_types.borrow_mut() =
387 collect_crate_types(sess, &krate.attrs);
388 *sess.crate_metadata.borrow_mut() =
389 collect_crate_metadata(sess, &krate.attrs);
391 time(time_passes, "recursion limit", (), |_| {
392 middle::recursion_limit::update_recursion_limit(sess, &krate);
395 // strip before expansion to allow macros to depend on
396 // configuration variables e.g/ in
398 // #[macro_use] #[cfg(foo)]
399 // mod bar { macro_rules! baz!(() => {{}}) }
401 // baz! should not use this definition unless foo is enabled.
403 krate = time(time_passes, "configuration 1", krate, |krate|
404 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate));
406 time(time_passes, "gated macro checking", (), |_| {
408 syntax::feature_gate::check_crate_macros(sess.codemap(),
409 &sess.parse_sess.span_diagnostic,
412 // these need to be set "early" so that expansion sees `quote` if enabled.
413 *sess.features.borrow_mut() = features;
414 sess.abort_if_errors();
418 krate = time(time_passes, "crate injection", krate, |krate|
419 syntax::std_inject::maybe_inject_crates_ref(krate,
420 sess.opts.alt_std_name.clone()));
422 let macros = time(time_passes, "macro loading", (), |_|
423 metadata::macro_import::read_macro_defs(sess, &krate));
425 let mut addl_plugins = Some(addl_plugins);
426 let registrars = time(time_passes, "plugin loading", (), |_|
427 plugin::load::load_plugins(sess, &krate, addl_plugins.take().unwrap()));
429 let mut registry = Registry::new(sess, &krate);
431 time(time_passes, "plugin registration", registrars, |registrars| {
432 if sess.features.borrow().rustc_diagnostic_macros {
433 registry.register_macro("__diagnostic_used",
434 diagnostics::plugin::expand_diagnostic_used);
435 registry.register_macro("__register_diagnostic",
436 diagnostics::plugin::expand_register_diagnostic);
437 registry.register_macro("__build_diagnostic_array",
438 diagnostics::plugin::expand_build_diagnostic_array);
441 for registrar in registrars {
442 registry.args_hidden = Some(registrar.args);
443 (registrar.fun)(&mut registry);
447 let Registry { syntax_exts, lint_passes, lint_groups, llvm_passes, .. } = registry;
450 let mut ls = sess.lint_store.borrow_mut();
451 for pass in lint_passes {
452 ls.register_pass(Some(sess), true, pass);
455 for (name, to) in lint_groups {
456 ls.register_group(Some(sess), true, name, to);
459 *sess.plugin_llvm_passes.borrow_mut() = llvm_passes;
462 // Lint plugins are registered; now we can process command line flags.
463 if sess.opts.describe_lints {
464 super::describe_lints(&*sess.lint_store.borrow(), true);
467 sess.lint_store.borrow_mut().process_command_line(sess);
469 // Abort if there are errors from lint processing or a plugin registrar.
470 sess.abort_if_errors();
472 krate = time(time_passes, "expansion", (krate, macros, syntax_exts),
473 |(krate, macros, syntax_exts)| {
474 // Windows dlls do not have rpaths, so they don't know how to find their
475 // dependencies. It's up to us to tell the system where to find all the
476 // dependent dlls. Note that this uses cfg!(windows) as opposed to
477 // targ_cfg because syntax extensions are always loaded for the host
478 // compiler, not for the target.
479 let mut _old_path = OsString::new();
481 _old_path = env::var_os("PATH").unwrap_or(_old_path);
482 let mut new_path = sess.host_filesearch(PathKind::All)
483 .get_dylib_search_paths();
484 new_path.extend(env::split_paths(&_old_path));
485 env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
487 let features = sess.features.borrow();
488 let cfg = syntax::ext::expand::ExpansionConfig {
489 crate_name: crate_name.to_string(),
490 features: Some(&features),
491 recursion_limit: sess.recursion_limit.get(),
492 trace_mac: sess.opts.debugging_opts.trace_macros,
494 let ret = syntax::ext::expand::expand_crate(&sess.parse_sess,
500 env::set_var("PATH", &_old_path);
506 // Needs to go *after* expansion to be able to check the results
507 // of macro expansion. This runs before #[cfg] to try to catch as
508 // much as possible (e.g. help the programmer avoid platform
509 // specific differences)
510 time(time_passes, "complete gated feature checking 1", (), |_| {
512 syntax::feature_gate::check_crate(sess.codemap(),
513 &sess.parse_sess.span_diagnostic,
515 *sess.features.borrow_mut() = features;
516 sess.abort_if_errors();
519 // JBC: make CFG processing part of expansion to avoid this problem:
521 // strip again, in case expansion added anything with a #[cfg].
522 krate = time(time_passes, "configuration 2", krate, |krate|
523 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate));
525 krate = time(time_passes, "maybe building test harness", krate, |krate|
526 syntax::test::modify_for_testing(&sess.parse_sess,
531 krate = time(time_passes, "prelude injection", krate, |krate|
532 syntax::std_inject::maybe_inject_prelude(krate));
534 time(time_passes, "checking that all macro invocations are gone", &krate, |krate|
535 syntax::ext::expand::check_for_macros(&sess.parse_sess, krate));
537 // One final feature gating of the true AST that gets compiled
538 // later, to make sure we've got everything (e.g. configuration
539 // can insert new attributes via `cfg_attr`)
540 time(time_passes, "complete gated feature checking 2", (), |_| {
542 syntax::feature_gate::check_crate(sess.codemap(),
543 &sess.parse_sess.span_diagnostic,
545 *sess.features.borrow_mut() = features;
546 sess.abort_if_errors();
552 pub fn assign_node_ids_and_map<'ast>(sess: &Session,
553 forest: &'ast mut ast_map::Forest)
554 -> ast_map::Map<'ast> {
555 struct NodeIdAssigner<'a> {
559 impl<'a> ast_map::FoldOps for NodeIdAssigner<'a> {
560 fn new_id(&self, old_id: ast::NodeId) -> ast::NodeId {
561 assert_eq!(old_id, ast::DUMMY_NODE_ID);
562 self.sess.next_node_id()
566 let map = time(sess.time_passes(), "assigning node ids and indexing ast", forest, |forest|
567 ast_map::map_crate(forest, NodeIdAssigner { sess: sess }));
569 if sess.opts.debugging_opts.ast_json {
570 println!("{}", json::as_json(map.krate()));
576 /// Run the resolution, typechecking, region checking and other
577 /// miscellaneous analysis passes on the crate. Return various
578 /// structures carrying the results of the analysis.
579 pub fn phase_3_run_analysis_passes<'tcx>(sess: Session,
580 ast_map: ast_map::Map<'tcx>,
581 arenas: &'tcx ty::CtxtArenas<'tcx>,
583 make_glob_map: resolve::MakeGlobMap)
584 -> ty::CrateAnalysis<'tcx> {
585 let time_passes = sess.time_passes();
586 let krate = ast_map.krate();
588 time(time_passes, "external crate/lib resolution", (), |_|
589 CrateReader::new(&sess).read_crates(krate));
591 let lang_items = time(time_passes, "language item collection", (), |_|
592 middle::lang_items::collect_language_items(krate, &sess));
594 let resolve::CrateMap {
602 time(time_passes, "resolution", (),
603 |_| resolve::resolve_crate(&sess,
609 // Discard MTWT tables that aren't required past resolution.
610 syntax::ext::mtwt::clear_tables();
612 let named_region_map = time(time_passes, "lifetime resolution", (),
613 |_| middle::resolve_lifetime::krate(&sess, krate, &def_map));
615 time(time_passes, "looking for entry point", (),
616 |_| middle::entry::find_entry_point(&sess, &ast_map));
618 sess.plugin_registrar_fn.set(
619 time(time_passes, "looking for plugin registrar", (), |_|
620 plugin::build::find_plugin_registrar(
621 sess.diagnostic(), krate)));
623 let region_map = time(time_passes, "region resolution", (), |_|
624 middle::region::resolve_crate(&sess, krate));
626 time(time_passes, "loop checking", (), |_|
627 middle::check_loop::check_crate(&sess, krate));
629 time(time_passes, "static item recursion checking", (), |_|
630 middle::check_static_recursion::check_crate(&sess, krate, &def_map, &ast_map));
632 let ty_cx = ty::mk_ctxt(sess,
640 stability::Index::new(krate));
642 // passes are timed inside typeck
643 typeck::check_crate(&ty_cx, trait_map);
645 time(time_passes, "const checking", (), |_|
646 middle::check_const::check_crate(&ty_cx));
648 let (exported_items, public_items) =
649 time(time_passes, "privacy checking", (), |_|
650 rustc_privacy::check_crate(&ty_cx, &export_map, external_exports));
652 // Do not move this check past lint
653 time(time_passes, "stability index", (), |_|
654 ty_cx.stability.borrow_mut().build(&ty_cx.sess, krate, &public_items));
656 time(time_passes, "intrinsic checking", (), |_|
657 middle::intrinsicck::check_crate(&ty_cx));
659 time(time_passes, "effect checking", (), |_|
660 middle::effect::check_crate(&ty_cx));
662 time(time_passes, "match checking", (), |_|
663 middle::check_match::check_crate(&ty_cx));
665 time(time_passes, "liveness checking", (), |_|
666 middle::liveness::check_crate(&ty_cx));
668 time(time_passes, "borrow checking", (), |_|
669 borrowck::check_crate(&ty_cx));
671 time(time_passes, "rvalue checking", (), |_|
672 middle::check_rvalues::check_crate(&ty_cx, krate));
674 // Avoid overwhelming user with errors if type checking failed.
675 // I'm not sure how helpful this is, to be honest, but it avoids a
676 // lot of annoying errors in the compile-fail tests (basically,
677 // lint warnings and so on -- kindck used to do this abort, but
678 // kindck is gone now). -nmatsakis
679 ty_cx.sess.abort_if_errors();
682 time(time_passes, "reachability checking", (), |_|
683 reachable::find_reachable(&ty_cx, &exported_items));
685 time(time_passes, "death checking", (), |_| {
686 middle::dead::check_crate(&ty_cx,
691 let ref lib_features_used =
692 time(time_passes, "stability checking", (), |_|
693 stability::check_unstable_api_usage(&ty_cx));
695 time(time_passes, "unused lib feature checking", (), |_|
696 stability::check_unused_or_stable_features(
697 &ty_cx.sess, lib_features_used));
699 time(time_passes, "lint checking", (), |_|
700 lint::check_crate(&ty_cx, &exported_items));
702 // The above three passes generate errors w/o aborting
703 ty_cx.sess.abort_if_errors();
706 export_map: export_map,
708 exported_items: exported_items,
709 public_items: public_items,
710 reachable: reachable_map,
716 /// Run the translation phase to LLVM, after which the AST and analysis can
718 pub fn phase_4_translate_to_llvm<'tcx>(analysis: ty::CrateAnalysis<'tcx>)
719 -> (ty::ctxt<'tcx>, trans::CrateTranslation) {
720 let time_passes = analysis.ty_cx.sess.time_passes();
722 time(time_passes, "resolving dependency formats", (), |_|
723 dependency_format::calculate(&analysis.ty_cx));
725 // Option dance to work around the lack of stack once closures.
726 time(time_passes, "translation", analysis, |analysis|
727 trans::trans_crate(analysis))
730 /// Run LLVM itself, producing a bitcode file, assembly file or object file
731 /// as a side effect.
732 pub fn phase_5_run_llvm_passes(sess: &Session,
733 trans: &trans::CrateTranslation,
734 outputs: &OutputFilenames) {
735 if sess.opts.cg.no_integrated_as {
736 let output_type = config::OutputTypeAssembly;
738 time(sess.time_passes(), "LLVM passes", (), |_|
739 write::run_passes(sess, trans, &[output_type], outputs));
741 write::run_assembler(sess, outputs);
743 // Remove assembly source, unless --save-temps was specified
744 if !sess.opts.cg.save_temps {
745 fs::remove_file(&outputs.temp_path(config::OutputTypeAssembly)).unwrap();
748 time(sess.time_passes(), "LLVM passes", (), |_|
749 write::run_passes(sess,
751 &sess.opts.output_types,
755 sess.abort_if_errors();
758 /// Run the linker on any artifacts that resulted from the LLVM run.
759 /// This should produce either a finished executable or library.
760 pub fn phase_6_link_output(sess: &Session,
761 trans: &trans::CrateTranslation,
762 outputs: &OutputFilenames) {
763 let old_path = env::var_os("PATH").unwrap_or(OsString::new());
764 let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths();
765 new_path.extend(env::split_paths(&old_path));
766 env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
768 time(sess.time_passes(), "linking", (), |_|
769 link::link_binary(sess,
772 &trans.link.crate_name));
774 env::set_var("PATH", &old_path);
777 fn escape_dep_filename(filename: &str) -> String {
778 // Apparently clang and gcc *only* escape spaces:
779 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
780 filename.replace(" ", "\\ ")
783 fn write_out_deps(sess: &Session,
785 outputs: &OutputFilenames,
788 let mut out_filenames = Vec::new();
789 for output_type in &sess.opts.output_types {
790 let file = outputs.path(*output_type);
792 config::OutputTypeExe => {
793 for output in &*sess.crate_types.borrow() {
794 let p = link::filename_for_input(sess, *output,
796 out_filenames.push(p);
799 _ => { out_filenames.push(file); }
803 // Write out dependency rules to the dep-info file if requested with
805 let deps_filename = match sess.opts.write_dependency_info {
806 // Use filename from --dep-file argument if given
807 (true, Some(ref filename)) => filename.clone(),
808 // Use default filename: crate source filename with extension replaced
810 (true, None) => match *input {
811 Input::File(..) => outputs.with_extension("d"),
813 sess.warn("can not write --dep-info without a filename \
814 when compiling stdin.");
821 let result = (|| -> io::Result<()> {
822 // Build a list of files used to compile the output and
823 // write Makefile-compatible dependency rules
824 let files: Vec<String> = sess.codemap().files.borrow()
826 .filter(|fmap| fmap.is_real_file())
827 .filter(|fmap| !fmap.is_imported())
828 .map(|fmap| escape_dep_filename(&fmap.name))
830 let mut file = try!(fs::File::create(&deps_filename));
831 for path in &out_filenames {
832 try!(write!(&mut file,
833 "{}: {}\n\n", path.display(), files.connect(" ")));
841 sess.fatal(&format!("error writing dependencies to `{}`: {}",
842 deps_filename.display(), e));
847 pub fn collect_crate_types(session: &Session,
848 attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
849 // Unconditionally collect crate types from attributes to make them used
850 let attr_types: Vec<config::CrateType> = attrs.iter().filter_map(|a| {
851 if a.check_name("crate_type") {
852 match a.value_str() {
853 Some(ref n) if *n == "rlib" => {
854 Some(config::CrateTypeRlib)
856 Some(ref n) if *n == "dylib" => {
857 Some(config::CrateTypeDylib)
859 Some(ref n) if *n == "lib" => {
860 Some(config::default_lib_output())
862 Some(ref n) if *n == "staticlib" => {
863 Some(config::CrateTypeStaticlib)
865 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
867 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
870 "invalid `crate_type` \
875 session.span_err(a.span, "`crate_type` requires a value");
876 session.note("for example: `#![crate_type=\"lib\"]`");
885 // If we're generating a test executable, then ignore all other output
886 // styles at all other locations
887 if session.opts.test {
888 return vec!(config::CrateTypeExecutable)
891 // Only check command line flags if present. If no types are specified by
892 // command line, then reuse the empty `base` Vec to hold the types that
893 // will be found in crate attributes.
894 let mut base = session.opts.crate_types.clone();
896 base.extend(attr_types.into_iter());
898 base.push(link::default_output_for_target(session));
904 base.into_iter().filter(|crate_type| {
905 let res = !link::invalid_output_for_target(session, *crate_type);
908 session.warn(&format!("dropping unsupported crate type `{}` \
910 *crate_type, session.opts.target_triple));
917 pub fn collect_crate_metadata(session: &Session,
918 _attrs: &[ast::Attribute]) -> Vec<String> {
919 session.opts.cg.metadata.clone()
922 pub fn build_output_filenames(input: &Input,
923 odir: &Option<PathBuf>,
924 ofile: &Option<PathBuf>,
925 attrs: &[ast::Attribute],
930 // "-" as input file will cause the parser to read from stdin so we
931 // have to make up a name
932 // We want to toss everything after the final '.'
933 let dirpath = match *odir {
934 Some(ref d) => d.clone(),
935 None => PathBuf::new()
938 // If a crate name is present, we use it as the link name
939 let stem = sess.opts.crate_name.clone().or_else(|| {
940 attr::find_crate_name(attrs).map(|n| n.to_string())
941 }).unwrap_or(input.filestem());
944 out_directory: dirpath,
946 single_output_file: None,
947 extra: sess.opts.cg.extra_filename.clone(),
951 Some(ref out_file) => {
952 let ofile = if sess.opts.output_types.len() > 1 {
953 sess.warn("ignoring specified output filename because multiple \
954 outputs were requested");
957 Some(out_file.clone())
960 sess.warn("ignoring --out-dir flag due to -o flag.");
963 let cur_dir = Path::new("");
966 out_directory: out_file.parent().unwrap_or(cur_dir).to_path_buf(),
967 out_filestem: out_file.file_stem().unwrap()
968 .to_str().unwrap().to_string(),
969 single_output_file: ofile,
970 extra: sess.opts.cg.extra_filename.clone(),