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;
34 use std::ffi::OsString;
40 use syntax::attr::{AttrMetaMethods};
41 use syntax::diagnostics;
43 use syntax::parse::token;
46 pub fn compile_input(sess: Session,
47 cfg: ast::CrateConfig,
49 outdir: &Option<Path>,
50 output: &Option<Path>,
51 addl_plugins: Option<Vec<String>>,
52 control: CompileController) {
53 macro_rules! controller_entry_point{($point: ident, $make_state: expr) => ({
55 let state = $make_state;
56 (control.$point.callback)(state);
58 if control.$point.stop {
63 // We need nested scopes here, because the intermediate results can keep
64 // large chunks of memory alive and we want to free them as soon as
65 // possible to keep the peak memory usage low
66 let (outputs, trans, sess) = {
67 let (outputs, expanded_crate, id) = {
68 let krate = phase_1_parse_input(&sess, cfg, input);
70 controller_entry_point!(after_parse,
71 CompileState::state_after_parse(input,
76 let outputs = build_output_filenames(input,
81 let id = link::find_crate_name(Some(&sess),
85 = match phase_2_configure_and_expand(&sess,
93 (outputs, expanded_crate, id)
96 controller_entry_point!(after_expand,
97 CompileState::state_after_expand(input,
103 let mut forest = ast_map::Forest::new(expanded_crate);
104 let arenas = ty::CtxtArenas::new();
105 let ast_map = assign_node_ids_and_map(&sess, &mut forest);
107 write_out_deps(&sess, input, &outputs, &id[]);
109 controller_entry_point!(after_write_deps,
110 CompileState::state_after_write_deps(input,
116 let analysis = phase_3_run_analysis_passes(sess,
120 control.make_glob_map);
122 controller_entry_point!(after_analysis,
123 CompileState::state_after_analysis(input,
124 &analysis.ty_cx.sess,
126 analysis.ty_cx.map.krate(),
130 if log_enabled!(::log::INFO) {
131 println!("Pre-trans");
132 analysis.ty_cx.print_debug_stats();
134 let (tcx, trans) = phase_4_translate_to_llvm(analysis);
136 if log_enabled!(::log::INFO) {
137 println!("Post-trans");
138 tcx.print_debug_stats();
141 // Discard interned strings as they are no longer required.
142 token::get_ident_interner().clear();
144 (outputs, trans, tcx.sess)
146 phase_5_run_llvm_passes(&sess, &trans, &outputs);
148 controller_entry_point!(after_llvm,
149 CompileState::state_after_llvm(input,
154 phase_6_link_output(&sess, &trans, &outputs);
157 /// The name used for source code that doesn't originate in a file
158 /// (e.g. source from stdin or a string)
159 pub fn anon_src() -> String {
163 pub fn source_name(input: &Input) -> String {
165 // FIXME (#9639): This needs to handle non-utf8 paths
166 Input::File(ref ifile) => ifile.as_str().unwrap().to_string(),
167 Input::Str(_) => anon_src()
171 /// CompileController is used to customise compilation, it allows compilation to
172 /// be stopped and/or to call arbitrary code at various points in compilation.
173 /// It also allows for various flags to be set to influence what information gets
174 /// colelcted during compilation.
176 /// This is a somewhat higher level controller than a Session - the Session
177 /// controls what happens in each phase, whereas the CompileController controls
178 /// whether a phase is run at all and whether other code (from outside the
179 /// the compiler) is run between phases.
181 /// Note that if compilation is set to stop and a callback is provided for a
182 /// given entry point, the callback is called before compilation is stopped.
184 /// Expect more entry points to be added in the future.
185 pub struct CompileController<'a> {
186 pub after_parse: PhaseController<'a>,
187 pub after_expand: PhaseController<'a>,
188 pub after_write_deps: PhaseController<'a>,
189 pub after_analysis: PhaseController<'a>,
190 pub after_llvm: PhaseController<'a>,
192 pub make_glob_map: resolve::MakeGlobMap,
195 impl<'a> CompileController<'a> {
196 pub fn basic() -> CompileController<'a> {
198 after_parse: PhaseController::basic(),
199 after_expand: PhaseController::basic(),
200 after_write_deps: PhaseController::basic(),
201 after_analysis: PhaseController::basic(),
202 after_llvm: PhaseController::basic(),
203 make_glob_map: resolve::MakeGlobMap::No,
208 pub struct PhaseController<'a> {
210 pub callback: Box<Fn(CompileState) -> () + 'a>,
213 impl<'a> PhaseController<'a> {
214 pub fn basic() -> PhaseController<'a> {
217 callback: box |&: _| {},
222 /// State that is passed to a callback. What state is available depends on when
223 /// during compilation the callback is made. See the various constructor methods
224 /// (`state_*`) in the impl to see which data is provided for any given entry point.
225 pub struct CompileState<'a, 'ast: 'a, 'tcx: 'a> {
226 pub input: &'a Input,
227 pub session: &'a Session,
228 pub cfg: Option<&'a ast::CrateConfig>,
229 pub krate: Option<&'a ast::Crate>,
230 pub crate_name: Option<&'a str>,
231 pub output_filenames: Option<&'a OutputFilenames>,
232 pub out_dir: Option<&'a Path>,
233 pub expanded_crate: Option<&'a ast::Crate>,
234 pub ast_map: Option<&'a ast_map::Map<'ast>>,
235 pub analysis: Option<&'a ty::CrateAnalysis<'tcx>>,
236 pub tcx: Option<&'a ty::ctxt<'tcx>>,
237 pub trans: Option<&'a trans::CrateTranslation>,
240 impl<'a, 'ast, 'tcx> CompileState<'a, 'ast, 'tcx> {
241 fn empty(input: &'a Input,
242 session: &'a Session,
243 out_dir: &'a Option<Path>)
244 -> CompileState<'a, 'ast, 'tcx> {
248 out_dir: out_dir.as_ref(),
252 output_filenames: None,
253 expanded_crate: None,
261 fn state_after_parse(input: &'a Input,
262 session: &'a Session,
263 out_dir: &'a Option<Path>,
264 krate: &'a ast::Crate)
265 -> CompileState<'a, 'ast, 'tcx> {
268 .. CompileState::empty(input, session, out_dir)
272 fn state_after_expand(input: &'a Input,
273 session: &'a Session,
274 out_dir: &'a Option<Path>,
275 expanded_crate: &'a ast::Crate,
277 -> CompileState<'a, 'ast, 'tcx> {
279 crate_name: Some(crate_name),
280 expanded_crate: Some(expanded_crate),
281 .. CompileState::empty(input, session, out_dir)
285 fn state_after_write_deps(input: &'a Input,
286 session: &'a Session,
287 out_dir: &'a Option<Path>,
288 ast_map: &'a ast_map::Map<'ast>,
290 -> CompileState<'a, 'ast, 'tcx> {
292 crate_name: Some(crate_name),
293 ast_map: Some(ast_map),
294 .. CompileState::empty(input, session, out_dir)
298 fn state_after_analysis(input: &'a Input,
299 session: &'a Session,
300 out_dir: &'a Option<Path>,
301 krate: &'a ast::Crate,
302 analysis: &'a ty::CrateAnalysis<'tcx>,
303 tcx: &'a ty::ctxt<'tcx>)
304 -> CompileState<'a, 'ast, 'tcx> {
306 analysis: Some(analysis),
309 .. CompileState::empty(input, session, out_dir)
314 fn state_after_llvm(input: &'a Input,
315 session: &'a Session,
316 out_dir: &'a Option<Path>,
317 trans: &'a trans::CrateTranslation)
318 -> CompileState<'a, 'ast, 'tcx> {
321 .. CompileState::empty(input, session, out_dir)
326 pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
328 // These may be left in an incoherent state after a previous compile.
329 // `clear_tables` and `get_ident_interner().clear()` can be used to free
330 // memory, but they do not restore the initial state.
331 syntax::ext::mtwt::reset_tables();
332 token::reset_ident_interner();
334 let krate = time(sess.time_passes(), "parsing", (), |_| {
336 Input::File(ref file) => {
337 parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
339 Input::Str(ref src) => {
340 parse::parse_crate_from_source_str(anon_src().to_string(),
348 if sess.opts.debugging_opts.ast_json_noexpand {
349 println!("{}", json::as_json(&krate));
352 if let Some(ref s) = sess.opts.show_span {
353 syntax::show_span::run(sess.diagnostic(), s.as_slice(), &krate);
359 // For continuing compilation after a parsed crate has been
362 /// Run the "early phases" of the compiler: initial `cfg` processing,
363 /// loading compiler plugins (including those from `addl_plugins`),
364 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
365 /// harness if one is to be provided and injection of a dependency on the
366 /// standard library and prelude.
368 /// Returns `None` if we're aborting after handling -W help.
369 pub fn phase_2_configure_and_expand(sess: &Session,
370 mut krate: ast::Crate,
372 addl_plugins: Option<Vec<String>>)
373 -> Option<ast::Crate> {
374 let time_passes = sess.time_passes();
376 *sess.crate_types.borrow_mut() =
377 collect_crate_types(sess, &krate.attrs[]);
378 *sess.crate_metadata.borrow_mut() =
379 collect_crate_metadata(sess, &krate.attrs[]);
381 time(time_passes, "recursion limit", (), |_| {
382 middle::recursion_limit::update_recursion_limit(sess, &krate);
385 // strip before expansion to allow macros to depend on
386 // configuration variables e.g/ in
388 // #[macro_use] #[cfg(foo)]
389 // mod bar { macro_rules! baz!(() => {{}}) }
391 // baz! should not use this definition unless foo is enabled.
393 time(time_passes, "gated macro checking", (), |_| {
395 syntax::feature_gate::check_crate_macros(sess.codemap(),
396 &sess.parse_sess.span_diagnostic,
399 // these need to be set "early" so that expansion sees `quote` if enabled.
400 *sess.features.borrow_mut() = features;
401 sess.abort_if_errors();
404 krate = time(time_passes, "configuration 1", krate, |krate|
405 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate));
407 krate = time(time_passes, "crate injection", krate, |krate|
408 syntax::std_inject::maybe_inject_crates_ref(krate,
409 sess.opts.alt_std_name.clone()));
411 let mut addl_plugins = Some(addl_plugins);
412 let Plugins { macros, registrars }
413 = time(time_passes, "plugin loading", (), |_|
414 plugin::load::load_plugins(sess, &krate, addl_plugins.take().unwrap()));
416 let mut registry = Registry::new(sess, &krate);
418 time(time_passes, "plugin registration", registrars, |registrars| {
419 if sess.features.borrow().rustc_diagnostic_macros {
420 registry.register_macro("__diagnostic_used",
421 diagnostics::plugin::expand_diagnostic_used);
422 registry.register_macro("__register_diagnostic",
423 diagnostics::plugin::expand_register_diagnostic);
424 registry.register_macro("__build_diagnostic_array",
425 diagnostics::plugin::expand_build_diagnostic_array);
428 for registrar in registrars.into_iter() {
429 registry.args_hidden = Some(registrar.args);
430 (registrar.fun)(&mut registry);
434 let Registry { syntax_exts, lint_passes, lint_groups, .. } = registry;
437 let mut ls = sess.lint_store.borrow_mut();
438 for pass in lint_passes.into_iter() {
439 ls.register_pass(Some(sess), true, pass);
442 for (name, to) in lint_groups.into_iter() {
443 ls.register_group(Some(sess), true, name, to);
447 // Lint plugins are registered; now we can process command line flags.
448 if sess.opts.describe_lints {
449 super::describe_lints(&*sess.lint_store.borrow(), true);
452 sess.lint_store.borrow_mut().process_command_line(sess);
454 // Abort if there are errors from lint processing or a plugin registrar.
455 sess.abort_if_errors();
457 krate = time(time_passes, "expansion", (krate, macros, syntax_exts),
458 |(krate, macros, syntax_exts)| {
459 // Windows dlls do not have rpaths, so they don't know how to find their
460 // dependencies. It's up to us to tell the system where to find all the
461 // dependent dlls. Note that this uses cfg!(windows) as opposed to
462 // targ_cfg because syntax extensions are always loaded for the host
463 // compiler, not for the target.
464 let mut _old_path = OsString::from_str("");
466 _old_path = env::var("PATH").unwrap_or(_old_path);
467 let mut new_path = sess.host_filesearch(PathKind::All).get_dylib_search_paths();
468 new_path.extend(env::split_paths(&_old_path));
469 env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
471 let cfg = syntax::ext::expand::ExpansionConfig {
472 crate_name: crate_name.to_string(),
473 enable_quotes: sess.features.borrow().quote,
474 recursion_limit: sess.recursion_limit.get(),
476 let ret = syntax::ext::expand::expand_crate(&sess.parse_sess,
482 env::set_var("PATH", &_old_path);
488 // Needs to go *after* expansion to be able to check the results of macro expansion.
489 time(time_passes, "complete gated feature checking", (), |_| {
491 syntax::feature_gate::check_crate(sess.codemap(),
492 &sess.parse_sess.span_diagnostic,
494 *sess.features.borrow_mut() = features;
495 sess.abort_if_errors();
498 // JBC: make CFG processing part of expansion to avoid this problem:
500 // strip again, in case expansion added anything with a #[cfg].
501 krate = time(time_passes, "configuration 2", krate, |krate|
502 syntax::config::strip_unconfigured_items(sess.diagnostic(), krate));
504 krate = time(time_passes, "maybe building test harness", krate, |krate|
505 syntax::test::modify_for_testing(&sess.parse_sess,
510 krate = time(time_passes, "prelude injection", krate, |krate|
511 syntax::std_inject::maybe_inject_prelude(krate));
513 time(time_passes, "checking that all macro invocations are gone", &krate, |krate|
514 syntax::ext::expand::check_for_macros(&sess.parse_sess, krate));
519 pub fn assign_node_ids_and_map<'ast>(sess: &Session,
520 forest: &'ast mut ast_map::Forest)
521 -> ast_map::Map<'ast> {
522 struct NodeIdAssigner<'a> {
526 impl<'a> ast_map::FoldOps for NodeIdAssigner<'a> {
527 fn new_id(&self, old_id: ast::NodeId) -> ast::NodeId {
528 assert_eq!(old_id, ast::DUMMY_NODE_ID);
529 self.sess.next_node_id()
533 let map = time(sess.time_passes(), "assigning node ids and indexing ast", forest, |forest|
534 ast_map::map_crate(forest, NodeIdAssigner { sess: sess }));
536 if sess.opts.debugging_opts.ast_json {
537 println!("{}", json::as_json(map.krate()));
543 /// Run the resolution, typechecking, region checking and other
544 /// miscellaneous analysis passes on the crate. Return various
545 /// structures carrying the results of the analysis.
546 pub fn phase_3_run_analysis_passes<'tcx>(sess: Session,
547 ast_map: ast_map::Map<'tcx>,
548 arenas: &'tcx ty::CtxtArenas<'tcx>,
550 make_glob_map: resolve::MakeGlobMap)
551 -> ty::CrateAnalysis<'tcx> {
552 let time_passes = sess.time_passes();
553 let krate = ast_map.krate();
555 time(time_passes, "external crate/lib resolution", (), |_|
556 CrateReader::new(&sess).read_crates(krate));
558 let lang_items = time(time_passes, "language item collection", (), |_|
559 middle::lang_items::collect_language_items(krate, &sess));
561 let resolve::CrateMap {
570 time(time_passes, "resolution", (),
571 |_| resolve::resolve_crate(&sess,
577 // Discard MTWT tables that aren't required past resolution.
578 syntax::ext::mtwt::clear_tables();
580 let named_region_map = time(time_passes, "lifetime resolution", (),
581 |_| middle::resolve_lifetime::krate(&sess, krate, &def_map));
583 time(time_passes, "looking for entry point", (),
584 |_| middle::entry::find_entry_point(&sess, &ast_map));
586 sess.plugin_registrar_fn.set(
587 time(time_passes, "looking for plugin registrar", (), |_|
588 plugin::build::find_plugin_registrar(
589 sess.diagnostic(), krate)));
591 let region_map = time(time_passes, "region resolution", (), |_|
592 middle::region::resolve_crate(&sess, krate));
594 time(time_passes, "loop checking", (), |_|
595 middle::check_loop::check_crate(&sess, krate));
597 let stability_index = time(time_passes, "stability index", (), |_|
598 stability::Index::build(&sess, krate));
600 time(time_passes, "static item recursion checking", (), |_|
601 middle::check_static_recursion::check_crate(&sess, krate, &def_map, &ast_map));
603 let ty_cx = ty::mk_ctxt(sess,
613 // passes are timed inside typeck
614 typeck::check_crate(&ty_cx, trait_map);
616 time(time_passes, "check static items", (), |_|
617 middle::check_static::check_crate(&ty_cx));
619 // These next two const passes can probably be merged
620 time(time_passes, "const marking", (), |_|
621 middle::const_eval::process_crate(&ty_cx));
623 time(time_passes, "const checking", (), |_|
624 middle::check_const::check_crate(&ty_cx));
626 let maps = (external_exports, last_private_map);
627 let (exported_items, public_items) =
628 time(time_passes, "privacy checking", maps, |(a, b)|
629 rustc_privacy::check_crate(&ty_cx, &export_map, a, b));
631 time(time_passes, "intrinsic checking", (), |_|
632 middle::intrinsicck::check_crate(&ty_cx));
634 time(time_passes, "effect checking", (), |_|
635 middle::effect::check_crate(&ty_cx));
637 time(time_passes, "match checking", (), |_|
638 middle::check_match::check_crate(&ty_cx));
640 time(time_passes, "liveness checking", (), |_|
641 middle::liveness::check_crate(&ty_cx));
643 time(time_passes, "borrow checking", (), |_|
644 borrowck::check_crate(&ty_cx));
646 time(time_passes, "rvalue checking", (), |_|
647 middle::check_rvalues::check_crate(&ty_cx, krate));
649 // Avoid overwhelming user with errors if type checking failed.
650 // I'm not sure how helpful this is, to be honest, but it avoids a
651 // lot of annoying errors in the compile-fail tests (basically,
652 // lint warnings and so on -- kindck used to do this abort, but
653 // kindck is gone now). -nmatsakis
654 ty_cx.sess.abort_if_errors();
657 time(time_passes, "reachability checking", (), |_|
658 reachable::find_reachable(&ty_cx, &exported_items));
660 time(time_passes, "death checking", (), |_| {
661 middle::dead::check_crate(&ty_cx,
666 let ref lib_features_used =
667 time(time_passes, "stability checking", (), |_|
668 stability::check_unstable_api_usage(&ty_cx));
670 time(time_passes, "unused feature checking", (), |_|
671 stability::check_unused_features(
672 &ty_cx.sess, lib_features_used));
674 time(time_passes, "lint checking", (), |_|
675 lint::check_crate(&ty_cx, &exported_items));
677 // The above three passes generate errors w/o aborting
678 ty_cx.sess.abort_if_errors();
681 export_map: export_map,
683 exported_items: exported_items,
684 public_items: public_items,
685 reachable: reachable_map,
691 /// Run the translation phase to LLVM, after which the AST and analysis can
693 pub fn phase_4_translate_to_llvm<'tcx>(analysis: ty::CrateAnalysis<'tcx>)
694 -> (ty::ctxt<'tcx>, trans::CrateTranslation) {
695 let time_passes = analysis.ty_cx.sess.time_passes();
697 time(time_passes, "resolving dependency formats", (), |_|
698 dependency_format::calculate(&analysis.ty_cx));
700 // Option dance to work around the lack of stack once closures.
701 time(time_passes, "translation", analysis, |analysis|
702 trans::trans_crate(analysis))
705 /// Run LLVM itself, producing a bitcode file, assembly file or object file
706 /// as a side effect.
707 pub fn phase_5_run_llvm_passes(sess: &Session,
708 trans: &trans::CrateTranslation,
709 outputs: &OutputFilenames) {
710 if sess.opts.cg.no_integrated_as {
711 let output_type = config::OutputTypeAssembly;
713 time(sess.time_passes(), "LLVM passes", (), |_|
714 write::run_passes(sess, trans, &[output_type], outputs));
716 write::run_assembler(sess, outputs);
718 // Remove assembly source, unless --save-temps was specified
719 if !sess.opts.cg.save_temps {
720 fs::unlink(&outputs.temp_path(config::OutputTypeAssembly)).unwrap();
723 time(sess.time_passes(), "LLVM passes", (), |_|
724 write::run_passes(sess,
726 &sess.opts.output_types[],
730 sess.abort_if_errors();
733 /// Run the linker on any artifacts that resulted from the LLVM run.
734 /// This should produce either a finished executable or library.
735 pub fn phase_6_link_output(sess: &Session,
736 trans: &trans::CrateTranslation,
737 outputs: &OutputFilenames) {
738 let old_path = env::var("PATH").unwrap_or(OsString::from_str(""));
739 let mut new_path = sess.host_filesearch(PathKind::All).get_tools_search_paths();
740 new_path.extend(env::split_paths(&old_path));
741 env::set_var("PATH", &env::join_paths(new_path.iter()).unwrap());
743 time(sess.time_passes(), "linking", (), |_|
744 link::link_binary(sess,
747 &trans.link.crate_name[]));
749 env::set_var("PATH", &old_path);
752 fn escape_dep_filename(filename: &str) -> String {
753 // Apparently clang and gcc *only* escape spaces:
754 // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
755 filename.replace(" ", "\\ ")
758 fn write_out_deps(sess: &Session,
760 outputs: &OutputFilenames,
763 let mut out_filenames = Vec::new();
764 for output_type in sess.opts.output_types.iter() {
765 let file = outputs.path(*output_type);
767 config::OutputTypeExe => {
768 for output in sess.crate_types.borrow().iter() {
769 let p = link::filename_for_input(sess, *output,
771 out_filenames.push(p);
774 _ => { out_filenames.push(file); }
778 // Write out dependency rules to the dep-info file if requested with
780 let deps_filename = match sess.opts.write_dependency_info {
781 // Use filename from --dep-file argument if given
782 (true, Some(ref filename)) => filename.clone(),
783 // Use default filename: crate source filename with extension replaced
785 (true, None) => match *input {
786 Input::File(..) => outputs.with_extension("d"),
788 sess.warn("can not write --dep-info without a filename \
789 when compiling stdin.");
796 let result = (|&:| -> old_io::IoResult<()> {
797 // Build a list of files used to compile the output and
798 // write Makefile-compatible dependency rules
799 let files: Vec<String> = sess.codemap().files.borrow()
800 .iter().filter(|fmap| fmap.is_real_file())
801 .map(|fmap| escape_dep_filename(&fmap.name[]))
803 let mut file = try!(old_io::File::create(&deps_filename));
804 for path in out_filenames.iter() {
805 try!(write!(&mut file as &mut Writer,
806 "{}: {}\n\n", path.display(), files.connect(" ")));
814 sess.fatal(&format!("error writing dependencies to `{}`: {}",
815 deps_filename.display(), e)[]);
820 pub fn collect_crate_types(session: &Session,
821 attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
822 // Unconditionally collect crate types from attributes to make them used
823 let attr_types: Vec<config::CrateType> = attrs.iter().filter_map(|a| {
824 if a.check_name("crate_type") {
825 match a.value_str() {
826 Some(ref n) if *n == "rlib" => {
827 Some(config::CrateTypeRlib)
829 Some(ref n) if *n == "dylib" => {
830 Some(config::CrateTypeDylib)
832 Some(ref n) if *n == "lib" => {
833 Some(config::default_lib_output())
835 Some(ref n) if *n == "staticlib" => {
836 Some(config::CrateTypeStaticlib)
838 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
840 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
843 "invalid `crate_type` \
848 session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
851 "`crate_type` requires a \
861 // If we're generating a test executable, then ignore all other output
862 // styles at all other locations
863 if session.opts.test {
864 return vec!(config::CrateTypeExecutable)
867 // Only check command line flags if present. If no types are specified by
868 // command line, then reuse the empty `base` Vec to hold the types that
869 // will be found in crate attributes.
870 let mut base = session.opts.crate_types.clone();
872 base.extend(attr_types.into_iter());
874 base.push(link::default_output_for_target(session));
880 base.into_iter().filter(|crate_type| {
881 let res = !link::invalid_output_for_target(session, *crate_type);
884 session.warn(&format!("dropping unsupported crate type `{}` \
886 *crate_type, session.opts.target_triple)[]);
893 pub fn collect_crate_metadata(session: &Session,
894 _attrs: &[ast::Attribute]) -> Vec<String> {
895 session.opts.cg.metadata.clone()
898 pub fn build_output_filenames(input: &Input,
900 ofile: &Option<Path>,
901 attrs: &[ast::Attribute],
906 // "-" as input file will cause the parser to read from stdin so we
907 // have to make up a name
908 // We want to toss everything after the final '.'
909 let dirpath = match *odir {
910 Some(ref d) => d.clone(),
911 None => Path::new(".")
914 // If a crate name is present, we use it as the link name
915 let stem = sess.opts.crate_name.clone().or_else(|| {
916 attr::find_crate_name(attrs).map(|n| n.get().to_string())
917 }).unwrap_or(input.filestem());
920 out_directory: dirpath,
922 single_output_file: None,
923 extra: sess.opts.cg.extra_filename.clone(),
927 Some(ref out_file) => {
928 let ofile = if sess.opts.output_types.len() > 1 {
929 sess.warn("ignoring specified output filename because multiple \
930 outputs were requested");
933 Some(out_file.clone())
936 sess.warn("ignoring --out-dir flag due to -o flag.");
939 out_directory: out_file.dir_path(),
940 out_filestem: out_file.filestem_str().unwrap().to_string(),
941 single_output_file: ofile,
942 extra: sess.opts.cg.extra_filename.clone(),