1 // Copyright 2012-2013 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;
15 use rustc::metadata::creader::CrateReader;
16 use rustc::middle::{stability, ty, reachable};
17 use rustc::middle::dependency_format;
19 use rustc::plugin::load::Plugins;
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;
38 use syntax::attr::{AttrMetaMethods};
39 use syntax::diagnostics;
41 use syntax::parse::token;
44 pub fn compile_input(sess: Session,
45 cfg: ast::CrateConfig,
47 outdir: &Option<Path>,
48 output: &Option<Path>,
49 addl_plugins: Option<Vec<String>>,
50 control: CompileController) {
51 macro_rules! controller_entry_point{($point: ident, $make_state: expr) => ({
53 let state = $make_state;
54 (control.$point.callback)(state);
56 if control.$point.stop {
61 // We need nested scopes here, because the intermediate results can keep
62 // large chunks of memory alive and we want to free them as soon as
63 // possible to keep the peak memory usage low
64 let (outputs, trans, sess) = {
65 let (outputs, expanded_crate, id) = {
66 let krate = phase_1_parse_input(&sess, cfg, input);
68 controller_entry_point!(after_parse,
69 CompileState::state_after_parse(input,
74 let outputs = build_output_filenames(input,
79 let id = link::find_crate_name(Some(&sess),
83 = match phase_2_configure_and_expand(&sess,
91 (outputs, expanded_crate, id)
94 controller_entry_point!(after_expand,
95 CompileState::state_after_expand(input,
101 let mut forest = ast_map::Forest::new(expanded_crate);
102 let ast_map = assign_node_ids_and_map(&sess, &mut forest);
104 write_out_deps(&sess, input, &outputs, &id[]);
106 let arenas = ty::CtxtArenas::new();
107 let analysis = phase_3_run_analysis_passes(sess,
111 control.make_glob_map);
113 controller_entry_point!(after_analysis,
114 CompileState::state_after_analysis(input,
115 &analysis.ty_cx.sess,
117 analysis.ty_cx.map.krate(),
121 if log_enabled!(::log::INFO) {
122 println!("Pre-trans");
123 analysis.ty_cx.print_debug_stats();
125 let (tcx, trans) = phase_4_translate_to_llvm(analysis);
127 if log_enabled!(::log::INFO) {
128 println!("Post-trans");
129 tcx.print_debug_stats();
132 // Discard interned strings as they are no longer required.
133 token::get_ident_interner().clear();
135 (outputs, trans, tcx.sess)
137 phase_5_run_llvm_passes(&sess, &trans, &outputs);
139 controller_entry_point!(after_llvm,
140 CompileState::state_after_llvm(input,
145 phase_6_link_output(&sess, &trans, &outputs);
148 /// The name used for source code that doesn't originate in a file
149 /// (e.g. source from stdin or a string)
150 pub fn anon_src() -> String {
154 pub fn source_name(input: &Input) -> String {
156 // FIXME (#9639): This needs to handle non-utf8 paths
157 Input::File(ref ifile) => ifile.as_str().unwrap().to_string(),
158 Input::Str(_) => anon_src()
162 /// CompileController is used to customise compilation, it allows compilation to
163 /// be stopped and/or to call arbitrary code at various points in compilation.
164 /// It also allows for various flags to be set to influence what information gets
165 /// colelcted during compilation.
167 /// This is a somewhat higher level controller than a Session - the Session
168 /// controls what happens in each phase, whereas the CompileController controls
169 /// whether a phase is run at all and whether other code (from outside the
170 /// the compiler) is run between phases.
172 /// Note that if compilation is set to stop and a callback is provided for a
173 /// given entry point, the callback is called before compilation is stopped.
175 /// Expect more entry points to be added in the future.
176 pub struct CompileController<'a> {
177 pub after_parse: PhaseController<'a>,
178 pub after_expand: PhaseController<'a>,
179 pub after_analysis: PhaseController<'a>,
180 pub after_llvm: PhaseController<'a>,
182 pub make_glob_map: resolve::MakeGlobMap,
185 impl<'a> CompileController<'a> {
186 pub fn basic() -> CompileController<'a> {
188 after_parse: PhaseController::basic(),
189 after_expand: PhaseController::basic(),
190 after_analysis: PhaseController::basic(),
191 after_llvm: PhaseController::basic(),
192 make_glob_map: resolve::MakeGlobMap::No,
197 pub struct PhaseController<'a> {
199 pub callback: Box<Fn(CompileState) -> () + 'a>,
202 impl<'a> PhaseController<'a> {
203 pub fn basic() -> PhaseController<'a> {
206 callback: box |&: _| {},
211 /// State that is passed to a callback. What state is available depends on when
212 /// during compilation the callback is made. See the various constructor methods
213 /// (`state_*`) in the impl to see which data is provided for any given entry point.
214 pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
215 pub input: &'a Input,
216 pub session: &'a Session,
217 pub cfg: Option<&'a ast::CrateConfig>,
218 pub krate: Option<&'a ast::Crate>,
219 pub crate_name: Option<&'a str>,
220 pub output_filenames: Option<&'a OutputFilenames>,
221 pub out_dir: Option<&'a Path>,
222 pub expanded_crate: Option<&'a ast::Crate>,
223 pub ast_map: Option<&'a ast_map::Map<'ast>>,
224 pub analysis: Option<&'a ty::CrateAnalysis<'tcx>>,
225 pub tcx: Option<&'a ty::ctxt<'tcx>>,
226 pub trans: Option<&'a trans::CrateTranslation>,
229 impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
230 fn empty(input: &'a Input,
231 session: &'a Session,
232 out_dir: &'a Option<Path>)
233 -> CompileState<'a, 'ast, 'tcx> {
237 out_dir: out_dir.as_ref(),
241 output_filenames: None,
242 expanded_crate: None,
250 fn state_after_parse(input: &'a Input,
251 session: &'a Session,
252 out_dir: &'a Option<Path>,
253 krate: &'a ast::Crate)
254 -> CompileState<'a, 'ast, 'tcx> {
257 .. CompileState::empty(input, session, out_dir)
261 fn state_after_expand(input: &'a Input,
262 session: &'a Session,
263 out_dir: &'a Option<Path>,
264 expanded_crate: &'a ast::Crate,
266 -> CompileState<'a, 'ast, 'tcx> {
268 crate_name: Some(crate_name),
269 expanded_crate: Some(expanded_crate),
270 .. CompileState::empty(input, session, out_dir)
274 fn state_after_analysis(input: &'a Input,
275 session: &'a Session,
276 out_dir: &'a Option<Path>,
277 krate: &'a ast::Crate,
278 analysis: &'a ty::CrateAnalysis<'tcx>,
279 tcx: &'a ty::ctxt<'tcx>)
280 -> CompileState<'a, 'ast, 'tcx> {
282 analysis: Some(analysis),
285 .. CompileState::empty(input, session, out_dir)
290 fn state_after_llvm(input: &'a Input,
291 session: &'a Session,
292 out_dir: &'a Option<Path>,
293 trans: &'a trans::CrateTranslation)
294 -> CompileState<'a, 'ast, 'tcx> {
297 .. CompileState::empty(input, session, out_dir)
302 pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
304 // These may be left in an incoherent state after a previous compile.
305 // `clear_tables` and `get_ident_interner().clear()` can be used to free
306 // memory, but they do not restore the initial state.
307 syntax::ext::mtwt::reset_tables();
308 token::reset_ident_interner();
310 let krate = time(sess.time_passes(), "parsing", (), |_| {
312 Input::File(ref file) => {
313 parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
315 Input::Str(ref src) => {
316 parse::parse_crate_from_source_str(anon_src().to_string(),
324 if sess.opts.debugging_opts.ast_json_noexpand {
325 println!("{}", json::as_json(&krate));
328 if let Some(ref s) = sess.opts.show_span {
329 syntax::show_span::run(sess.diagnostic(), s.as_slice(), &krate);
335 // For continuing compilation after a parsed crate has been
338 /// Run the "early phases" of the compiler: initial `cfg` processing,
339 /// loading compiler plugins (including those from `addl_plugins`),
340 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
341 /// harness if one is to be provided and injection of a dependency on the
342 /// standard library and prelude.
344 /// Returns `None` if we're aborting after handling -W help.
345 pub fn phase_2_configure_and_expand(sess: &Session,
346 mut krate: ast::Crate,
348 addl_plugins: Option<Vec<String>>)
349 -> Option<ast::Crate> {
350 let time_passes = sess.time_passes();
352 *sess.crate_types.borrow_mut() =
353 collect_crate_types(sess, &krate.attrs[]);
354 *sess.crate_metadata.borrow_mut() =
355 collect_crate_metadata(sess, &krate.attrs[]);
357 time(time_passes, "recursion limit", (), |_| {
358 middle::recursion_limit::update_recursion_limit(sess, &krate);
361 // strip before expansion to allow macros to depend on
362 // configuration variables e.g/ in
364 // #[macro_use] #[cfg(foo)]
365 // mod bar { macro_rules! baz!(() => {{}}) }
367 // baz! should not use this definition unless foo is enabled.
369 time(time_passes, "gated macro checking", (), |_| {
370 let (features, unknown_features) =
371 syntax::feature_gate::check_crate_macros(sess.codemap(),
372 &sess.parse_sess.span_diagnostic,
374 for uf in unknown_features.iter() {
375 sess.add_lint(lint::builtin::UNKNOWN_FEATURES,
378 "unknown feature".to_string());
381 // these need to be set "early" so that expansion sees `quote` if enabled.
382 *sess.features.borrow_mut() = features;
383 sess.abort_if_errors();
386 krate = time(time_passes, "configuration 1", krate, |krate|
387 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate));
389 krate = time(time_passes, "crate injection", krate, |krate|
390 syntax::std_inject::maybe_inject_crates_ref(krate,
391 sess.opts.alt_std_name.clone()));
393 let mut addl_plugins = Some(addl_plugins);
394 let Plugins { macros, registrars }
395 = time(time_passes, "plugin loading", (), |_|
396 plugin::load::load_plugins(sess, &krate, addl_plugins.take().unwrap()));
398 let mut registry = Registry::new(sess, &krate);
400 time(time_passes, "plugin registration", registrars, |registrars| {
401 if sess.features.borrow().rustc_diagnostic_macros {
402 registry.register_macro("__diagnostic_used",
403 diagnostics::plugin::expand_diagnostic_used);
404 registry.register_macro("__register_diagnostic",
405 diagnostics::plugin::expand_register_diagnostic);
406 registry.register_macro("__build_diagnostic_array",
407 diagnostics::plugin::expand_build_diagnostic_array);
410 for registrar in registrars.into_iter() {
411 registry.args_hidden = Some(registrar.args);
412 (registrar.fun)(&mut registry);
416 let Registry { syntax_exts, lint_passes, lint_groups, .. } = registry;
419 let mut ls = sess.lint_store.borrow_mut();
420 for pass in lint_passes.into_iter() {
421 ls.register_pass(Some(sess), true, pass);
424 for (name, to) in lint_groups.into_iter() {
425 ls.register_group(Some(sess), true, name, to);
429 // Lint plugins are registered; now we can process command line flags.
430 if sess.opts.describe_lints {
431 super::describe_lints(&*sess.lint_store.borrow(), true);
434 sess.lint_store.borrow_mut().process_command_line(sess);
436 // Abort if there are errors from lint processing or a plugin registrar.
437 sess.abort_if_errors();
439 krate = time(time_passes, "expansion", (krate, macros, syntax_exts),
440 |(krate, macros, syntax_exts)| {
441 // Windows dlls do not have rpaths, so they don't know how to find their
442 // dependencies. It's up to us to tell the system where to find all the
443 // dependent dlls. Note that this uses cfg!(windows) as opposed to
444 // targ_cfg because syntax extensions are always loaded for the host
445 // compiler, not for the target.
446 let mut _old_path = String::new();
448 _old_path = os::getenv("PATH").unwrap_or(_old_path);
449 let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths();
450 new_path.extend(os::split_paths(&_old_path[]).into_iter());
451 os::setenv("PATH", os::join_paths(&new_path[]).unwrap());
453 let cfg = syntax::ext::expand::ExpansionConfig {
454 crate_name: crate_name.to_string(),
455 enable_quotes: sess.features.borrow().quote,
456 recursion_limit: sess.recursion_limit.get(),
458 let ret = syntax::ext::expand::expand_crate(&sess.parse_sess,
464 os::setenv("PATH", _old_path);
470 // Needs to go *after* expansion to be able to check the results of macro expansion.
471 time(time_passes, "complete gated feature checking", (), |_| {
472 syntax::feature_gate::check_crate(sess.codemap(),
473 &sess.parse_sess.span_diagnostic,
475 sess.abort_if_errors();
478 // JBC: make CFG processing part of expansion to avoid this problem:
480 // strip again, in case expansion added anything with a #[cfg].
481 krate = time(time_passes, "configuration 2", krate, |krate|
482 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate));
484 krate = time(time_passes, "maybe building test harness", krate, |krate|
485 syntax::test::modify_for_testing(&sess.parse_sess,
490 krate = time(time_passes, "prelude injection", krate, |krate|
491 syntax::std_inject::maybe_inject_prelude(krate));
493 time(time_passes, "checking that all macro invocations are gone", &krate, |krate|
494 syntax::ext::expand::check_for_macros(&sess.parse_sess, krate));
499 pub fn assign_node_ids_and_map<'ast>(sess: &Session,
500 forest: &'ast mut ast_map::Forest)
501 -> ast_map::Map<'ast> {
502 struct NodeIdAssigner<'a> {
506 impl<'a> ast_map::FoldOps for NodeIdAssigner<'a> {
507 fn new_id(&self, old_id: ast::NodeId) -> ast::NodeId {
508 assert_eq!(old_id, ast::DUMMY_NODE_ID);
509 self.sess.next_node_id()
513 let map = time(sess.time_passes(), "assigning node ids and indexing ast", forest, |forest|
514 ast_map::map_crate(forest, NodeIdAssigner { sess: sess }));
516 if sess.opts.debugging_opts.ast_json {
517 println!("{}", json::as_json(map.krate()));
523 /// Run the resolution, typechecking, region checking and other
524 /// miscellaneous analysis passes on the crate. Return various
525 /// structures carrying the results of the analysis.
526 pub fn phase_3_run_analysis_passes<'tcx>(sess: Session,
527 ast_map: ast_map::Map<'tcx>,
528 arenas: &'tcx ty::CtxtArenas<'tcx>,
530 make_glob_map: resolve::MakeGlobMap)
531 -> ty::CrateAnalysis<'tcx> {
532 let time_passes = sess.time_passes();
533 let krate = ast_map.krate();
535 time(time_passes, "external crate/lib resolution", (), |_|
536 CrateReader::new(&sess).read_crates(krate));
538 let lang_items = time(time_passes, "language item collection", (), |_|
539 middle::lang_items::collect_language_items(krate, &sess));
541 let resolve::CrateMap {
551 time(time_passes, "resolution", (),
552 |_| resolve::resolve_crate(&sess,
558 // Discard MTWT tables that aren't required past resolution.
559 syntax::ext::mtwt::clear_tables();
561 let named_region_map = time(time_passes, "lifetime resolution", (),
562 |_| middle::resolve_lifetime::krate(&sess, krate, &def_map));
564 time(time_passes, "looking for entry point", (),
565 |_| middle::entry::find_entry_point(&sess, &ast_map));
567 sess.plugin_registrar_fn.set(
568 time(time_passes, "looking for plugin registrar", (), |_|
569 plugin::build::find_plugin_registrar(
570 sess.diagnostic(), krate)));
572 let region_map = time(time_passes, "region resolution", (), |_|
573 middle::region::resolve_crate(&sess, krate));
575 time(time_passes, "loop checking", (), |_|
576 middle::check_loop::check_crate(&sess, krate));
578 let stability_index = time(time_passes, "stability index", (), |_|
579 stability::Index::build(krate));
581 time(time_passes, "static item recursion checking", (), |_|
582 middle::check_static_recursion::check_crate(&sess, krate, &def_map, &ast_map));
584 let ty_cx = ty::mk_ctxt(sess,
595 // passes are timed inside typeck
596 typeck::check_crate(&ty_cx, trait_map);
598 time(time_passes, "check static items", (), |_|
599 middle::check_static::check_crate(&ty_cx));
601 // These next two const passes can probably be merged
602 time(time_passes, "const marking", (), |_|
603 middle::const_eval::process_crate(&ty_cx));
605 time(time_passes, "const checking", (), |_|
606 middle::check_const::check_crate(&ty_cx));
608 let maps = (external_exports, last_private_map);
609 let (exported_items, public_items) =
610 time(time_passes, "privacy checking", maps, |(a, b)|
611 middle::privacy::check_crate(&ty_cx, &export_map, a, b));
613 time(time_passes, "intrinsic checking", (), |_|
614 middle::intrinsicck::check_crate(&ty_cx));
616 time(time_passes, "effect checking", (), |_|
617 middle::effect::check_crate(&ty_cx));
619 time(time_passes, "match checking", (), |_|
620 middle::check_match::check_crate(&ty_cx));
622 time(time_passes, "liveness checking", (), |_|
623 middle::liveness::check_crate(&ty_cx));
625 time(time_passes, "borrow checking", (), |_|
626 borrowck::check_crate(&ty_cx));
628 time(time_passes, "rvalue checking", (), |_|
629 middle::check_rvalues::check_crate(&ty_cx, krate));
631 // Avoid overwhelming user with errors if type checking failed.
632 // I'm not sure how helpful this is, to be honest, but it avoids a
633 // lot of annoying errors in the compile-fail tests (basically,
634 // lint warnings and so on -- kindck used to do this abort, but
635 // kindck is gone now). -nmatsakis
636 ty_cx.sess.abort_if_errors();
639 time(time_passes, "reachability checking", (), |_|
640 reachable::find_reachable(&ty_cx, &exported_items));
642 time(time_passes, "death checking", (), |_| {
643 middle::dead::check_crate(&ty_cx,
648 time(time_passes, "lint checking", (), |_|
649 lint::check_crate(&ty_cx, &exported_items));
652 export_map: export_map,
654 exported_items: exported_items,
655 public_items: public_items,
656 reachable: reachable_map,
662 /// Run the translation phase to LLVM, after which the AST and analysis can
664 pub fn phase_4_translate_to_llvm<'tcx>(analysis: ty::CrateAnalysis<'tcx>)
665 -> (ty::ctxt<'tcx>, trans::CrateTranslation) {
666 let time_passes = analysis.ty_cx.sess.time_passes();
668 time(time_passes, "resolving dependency formats", (), |_|
669 dependency_format::calculate(&analysis.ty_cx));
671 // Option dance to work around the lack of stack once closures.
672 time(time_passes, "translation", analysis, |analysis|
673 trans::trans_crate(analysis))
676 /// Run LLVM itself, producing a bitcode file, assembly file or object file
677 /// as a side effect.
678 pub fn phase_5_run_llvm_passes(sess: &Session,
679 trans: &trans::CrateTranslation,
680 outputs: &OutputFilenames) {
681 if sess.opts.cg.no_integrated_as {
682 let output_type = config::OutputTypeAssembly;
684 time(sess.time_passes(), "LLVM passes", (), |_|
685 write::run_passes(sess, trans, &[output_type], outputs));
687 write::run_assembler(sess, outputs);
689 // Remove assembly source, unless --save-temps was specified
690 if !sess.opts.cg.save_temps {
691 fs::unlink(&outputs.temp_path(config::OutputTypeAssembly)).unwrap();
694 time(sess.time_passes(), "LLVM passes", (), |_|
695 write::run_passes(sess,
697 &sess.opts.output_types[],
701 sess.abort_if_errors();
704 /// Run the linker on any artifacts that resulted from the LLVM run.
705 /// This should produce either a finished executable or library.
706 pub fn phase_6_link_output(sess: &Session,
707 trans: &trans::CrateTranslation,
708 outputs: &OutputFilenames) {
709 let old_path = os::getenv("PATH").unwrap_or_else(||String::new());
710 let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths();
711 new_path.extend(os::split_paths(&old_path[]).into_iter());
712 os::setenv("PATH", os::join_paths(&new_path[]).unwrap());
714 time(sess.time_passes(), "linking", (), |_|
715 link::link_binary(sess,
718 &trans.link.crate_name[]));
720 os::setenv("PATH", old_path);
723 fn escape_dep_filename(filename: &str) -> String {
724 // Apparently clang and gcc *only* escape spaces:
725 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
726 filename.replace(" ", "\\ ")
729 fn write_out_deps(sess: &Session,
731 outputs: &OutputFilenames,
734 let mut out_filenames = Vec::new();
735 for output_type in sess.opts.output_types.iter() {
736 let file = outputs.path(*output_type);
738 config::OutputTypeExe => {
739 for output in sess.crate_types.borrow().iter() {
740 let p = link::filename_for_input(sess, *output,
742 out_filenames.push(p);
745 _ => { out_filenames.push(file); }
749 // Write out dependency rules to the dep-info file if requested with
751 let deps_filename = match sess.opts.write_dependency_info {
752 // Use filename from --dep-file argument if given
753 (true, Some(ref filename)) => filename.clone(),
754 // Use default filename: crate source filename with extension replaced
756 (true, None) => match *input {
757 Input::File(..) => outputs.with_extension("d"),
759 sess.warn("can not write --dep-info without a filename \
760 when compiling stdin.");
767 let result = (|&:| -> io::IoResult<()> {
768 // Build a list of files used to compile the output and
769 // write Makefile-compatible dependency rules
770 let files: Vec<String> = sess.codemap().files.borrow()
771 .iter().filter(|fmap| fmap.is_real_file())
772 .map(|fmap| escape_dep_filename(&fmap.name[]))
774 let mut file = try!(io::File::create(&deps_filename));
775 for path in out_filenames.iter() {
776 try!(write!(&mut file as &mut Writer,
777 "{}: {}\n\n", path.display(), files.connect(" ")));
785 sess.fatal(&format!("error writing dependencies to `{}`: {}",
786 deps_filename.display(), e)[]);
791 pub fn collect_crate_types(session: &Session,
792 attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
793 // Unconditionally collect crate types from attributes to make them used
794 let attr_types: Vec<config::CrateType> = attrs.iter().filter_map(|a| {
795 if a.check_name("crate_type") {
796 match a.value_str() {
797 Some(ref n) if *n == "rlib" => {
798 Some(config::CrateTypeRlib)
800 Some(ref n) if *n == "dylib" => {
801 Some(config::CrateTypeDylib)
803 Some(ref n) if *n == "lib" => {
804 Some(config::default_lib_output())
806 Some(ref n) if *n == "staticlib" => {
807 Some(config::CrateTypeStaticlib)
809 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
811 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
814 "invalid `crate_type` \
819 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
822 "`crate_type` requires a \
832 // If we're generating a test executable, then ignore all other output
833 // styles at all other locations
834 if session.opts.test {
835 return vec!(config::CrateTypeExecutable)
838 // Only check command line flags if present. If no types are specified by
839 // command line, then reuse the empty `base` Vec to hold the types that
840 // will be found in crate attributes.
841 let mut base = session.opts.crate_types.clone();
843 base.extend(attr_types.into_iter());
845 base.push(link::default_output_for_target(session));
851 base.into_iter().filter(|crate_type| {
852 let res = !link::invalid_output_for_target(session, *crate_type);
855 session.warn(&format!("dropping unsupported crate type `{:?}` \
857 *crate_type, session.opts.target_triple)[]);
864 pub fn collect_crate_metadata(session: &Session,
865 _attrs: &[ast::Attribute]) -> Vec<String> {
866 session.opts.cg.metadata.clone()
869 pub fn build_output_filenames(input: &Input,
871 ofile: &Option<Path>,
872 attrs: &[ast::Attribute],
877 // "-" as input file will cause the parser to read from stdin so we
878 // have to make up a name
879 // We want to toss everything after the final '.'
880 let dirpath = match *odir {
881 Some(ref d) => d.clone(),
882 None => Path::new(".")
885 // If a crate name is present, we use it as the link name
886 let stem = sess.opts.crate_name.clone().or_else(|| {
887 attr::find_crate_name(attrs).map(|n| n.get().to_string())
888 }).unwrap_or(input.filestem());
891 out_directory: dirpath,
893 single_output_file: None,
894 extra: sess.opts.cg.extra_filename.clone(),
898 Some(ref out_file) => {
899 let ofile = if sess.opts.output_types.len() > 1 {
900 sess.warn("ignoring specified output filename because multiple \
901 outputs were requested");
904 Some(out_file.clone())
907 sess.warn("ignoring --out-dir flag due to -o flag.");
910 out_directory: out_file.dir_path(),
911 out_filestem: out_file.filestem_str().unwrap().to_string(),
912 single_output_file: ofile,
913 extra: sess.opts.cg.extra_filename.clone(),