]> git.lizzy.rs Git - rust.git/blob - src/librustc_driver/driver.rs
auto merge of #19628 : jbranchaud/rust/add-string-as-string-doctest, r=steveklabnik
[rust.git] / src / librustc_driver / driver.rs
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.
4 //
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.
10
11 use rustc::session::Session;
12 use rustc::session::config::{mod, Input, OutputFilenames};
13 use rustc::lint;
14 use rustc::metadata::creader;
15 use rustc::middle::{stability, ty, reachable};
16 use rustc::middle::dependency_format;
17 use rustc::middle;
18 use rustc::plugin::load::Plugins;
19 use rustc::plugin::registry::Registry;
20 use rustc::plugin;
21 use rustc::util::common::time;
22 use rustc_trans::back::link;
23 use rustc_trans::back::write;
24 use rustc_trans::save;
25 use rustc_trans::trans;
26 use rustc_typeck as typeck;
27
28 use serialize::{json, Encodable};
29
30 use std::io;
31 use std::io::fs;
32 use std::os;
33 use arena::TypedArena;
34 use syntax::ast;
35 use syntax::ast_map;
36 use syntax::attr;
37 use syntax::attr::{AttrMetaMethods};
38 use syntax::diagnostics;
39 use syntax::parse;
40 use syntax::parse::token;
41 use syntax;
42
43 pub fn compile_input(sess: Session,
44                      cfg: ast::CrateConfig,
45                      input: &Input,
46                      outdir: &Option<Path>,
47                      output: &Option<Path>,
48                      addl_plugins: Option<Plugins>) {
49     // These may be left in an incoherent state after a previous compile.
50     // `clear_tables` and `get_ident_interner().clear()` can be used to free
51     // memory, but they do not restore the initial state.
52     syntax::ext::mtwt::reset_tables();
53     token::reset_ident_interner();
54
55     // We need nested scopes here, because the intermediate results can keep
56     // large chunks of memory alive and we want to free them as soon as
57     // possible to keep the peak memory usage low
58     let (outputs, trans, sess) = {
59         let (outputs, expanded_crate, id) = {
60             let krate = phase_1_parse_input(&sess, cfg, input);
61             if stop_after_phase_1(&sess) { return; }
62             let outputs = build_output_filenames(input,
63                                                  outdir,
64                                                  output,
65                                                  krate.attrs.as_slice(),
66                                                  &sess);
67             let id = link::find_crate_name(Some(&sess), krate.attrs.as_slice(),
68                                            input);
69             let expanded_crate
70                 = match phase_2_configure_and_expand(&sess, krate, id.as_slice(),
71                                                      addl_plugins) {
72                     None => return,
73                     Some(k) => k
74                 };
75
76             (outputs, expanded_crate, id)
77         };
78
79         let mut forest = ast_map::Forest::new(expanded_crate);
80         let ast_map = assign_node_ids_and_map(&sess, &mut forest);
81
82         write_out_deps(&sess, input, &outputs, id.as_slice());
83
84         if stop_after_phase_2(&sess) { return; }
85
86         let type_arena = TypedArena::new();
87         let analysis = phase_3_run_analysis_passes(sess, ast_map, &type_arena, id);
88         phase_save_analysis(&analysis.ty_cx.sess, analysis.ty_cx.map.krate(), &analysis, outdir);
89         if stop_after_phase_3(&analysis.ty_cx.sess) { return; }
90         let (tcx, trans) = phase_4_translate_to_llvm(analysis);
91
92         // Discard interned strings as they are no longer required.
93         token::get_ident_interner().clear();
94
95         (outputs, trans, tcx.sess)
96     };
97     phase_5_run_llvm_passes(&sess, &trans, &outputs);
98     if stop_after_phase_5(&sess) { return; }
99     phase_6_link_output(&sess, &trans, &outputs);
100 }
101
102 /// The name used for source code that doesn't originate in a file
103 /// (e.g. source from stdin or a string)
104 pub fn anon_src() -> String {
105     "<anon>".to_string()
106 }
107
108 pub fn source_name(input: &Input) -> String {
109     match *input {
110         // FIXME (#9639): This needs to handle non-utf8 paths
111         Input::File(ref ifile) => ifile.as_str().unwrap().to_string(),
112         Input::Str(_) => anon_src()
113     }
114 }
115
116 pub fn phase_1_parse_input(sess: &Session, cfg: ast::CrateConfig, input: &Input)
117     -> ast::Crate {
118     let krate = time(sess.time_passes(), "parsing", (), |_| {
119         match *input {
120             Input::File(ref file) => {
121                 parse::parse_crate_from_file(&(*file), cfg.clone(), &sess.parse_sess)
122             }
123             Input::Str(ref src) => {
124                 parse::parse_crate_from_source_str(anon_src().to_string(),
125                                                    src.to_string(),
126                                                    cfg.clone(),
127                                                    &sess.parse_sess)
128             }
129         }
130     });
131
132     if sess.opts.debugging_opts & config::AST_JSON_NOEXPAND != 0 {
133         let mut stdout = io::BufferedWriter::new(io::stdout());
134         let mut json = json::PrettyEncoder::new(&mut stdout);
135         // unwrapping so IoError isn't ignored
136         krate.encode(&mut json).unwrap();
137     }
138
139     if sess.show_span() {
140         syntax::show_span::run(sess.diagnostic(), &krate);
141     }
142
143     krate
144 }
145
146 // For continuing compilation after a parsed crate has been
147 // modified
148
149 /// Run the "early phases" of the compiler: initial `cfg` processing,
150 /// loading compiler plugins (including those from `addl_plugins`),
151 /// syntax expansion, secondary `cfg` expansion, synthesis of a test
152 /// harness if one is to be provided and injection of a dependency on the
153 /// standard library and prelude.
154 ///
155 /// Returns `None` if we're aborting after handling -W help.
156 pub fn phase_2_configure_and_expand(sess: &Session,
157                                     mut krate: ast::Crate,
158                                     crate_name: &str,
159                                     addl_plugins: Option<Plugins>)
160                                     -> Option<ast::Crate> {
161     let time_passes = sess.time_passes();
162
163     *sess.crate_types.borrow_mut() =
164         collect_crate_types(sess, krate.attrs.as_slice());
165     *sess.crate_metadata.borrow_mut() =
166         collect_crate_metadata(sess, krate.attrs.as_slice());
167
168     time(time_passes, "gated feature checking", (), |_| {
169         let (features, unknown_features) =
170             syntax::feature_gate::check_crate(&sess.parse_sess.span_diagnostic, &krate);
171
172         for uf in unknown_features.iter() {
173             sess.add_lint(lint::builtin::UNKNOWN_FEATURES,
174                           ast::CRATE_NODE_ID,
175                           *uf,
176                           "unknown feature".to_string());
177         }
178
179         sess.abort_if_errors();
180         *sess.features.borrow_mut() = features;
181     });
182
183     time(time_passes, "recursion limit", (), |_| {
184         middle::recursion_limit::update_recursion_limit(sess, &krate);
185     });
186
187     // strip before expansion to allow macros to depend on
188     // configuration variables e.g/ in
189     //
190     //   #[macro_escape] #[cfg(foo)]
191     //   mod bar { macro_rules! baz!(() => {{}}) }
192     //
193     // baz! should not use this definition unless foo is enabled.
194
195     krate = time(time_passes, "configuration 1", krate, |krate|
196                  syntax::config::strip_unconfigured_items(sess.diagnostic(), krate));
197
198     krate = time(time_passes, "crate injection", krate, |krate|
199                  syntax::std_inject::maybe_inject_crates_ref(krate,
200                                                              sess.opts.alt_std_name.clone()));
201
202     let mut addl_plugins = Some(addl_plugins);
203     let Plugins { macros, registrars }
204         = time(time_passes, "plugin loading", (), |_|
205                plugin::load::load_plugins(sess, &krate, addl_plugins.take().unwrap()));
206
207     let mut registry = Registry::new(&krate);
208
209     time(time_passes, "plugin registration", (), |_| {
210         if sess.features.borrow().rustc_diagnostic_macros {
211             registry.register_macro("__diagnostic_used",
212                 diagnostics::plugin::expand_diagnostic_used);
213             registry.register_macro("__register_diagnostic",
214                 diagnostics::plugin::expand_register_diagnostic);
215             registry.register_macro("__build_diagnostic_array",
216                 diagnostics::plugin::expand_build_diagnostic_array);
217         }
218
219         for &registrar in registrars.iter() {
220             registrar(&mut registry);
221         }
222     });
223
224     let Registry { syntax_exts, lint_passes, lint_groups, .. } = registry;
225
226     {
227         let mut ls = sess.lint_store.borrow_mut();
228         for pass in lint_passes.into_iter() {
229             ls.register_pass(Some(sess), true, pass);
230         }
231
232         for (name, to) in lint_groups.into_iter() {
233             ls.register_group(Some(sess), true, name, to);
234         }
235     }
236
237     // Lint plugins are registered; now we can process command line flags.
238     if sess.opts.describe_lints {
239         super::describe_lints(&*sess.lint_store.borrow(), true);
240         return None;
241     }
242     sess.lint_store.borrow_mut().process_command_line(sess);
243
244     // Abort if there are errors from lint processing or a plugin registrar.
245     sess.abort_if_errors();
246
247     krate = time(time_passes, "expansion", (krate, macros, syntax_exts),
248         |(krate, macros, syntax_exts)| {
249             // Windows dlls do not have rpaths, so they don't know how to find their
250             // dependencies. It's up to us to tell the system where to find all the
251             // dependent dlls. Note that this uses cfg!(windows) as opposed to
252             // targ_cfg because syntax extensions are always loaded for the host
253             // compiler, not for the target.
254             let mut _old_path = String::new();
255             if cfg!(windows) {
256                 _old_path = os::getenv("PATH").unwrap_or(_old_path);
257                 let mut new_path = sess.host_filesearch().get_dylib_search_paths();
258                 new_path.extend(os::split_paths(_old_path.as_slice()).into_iter());
259                 os::setenv("PATH", os::join_paths(new_path.as_slice()).unwrap());
260             }
261             let cfg = syntax::ext::expand::ExpansionConfig {
262                 crate_name: crate_name.to_string(),
263                 deriving_hash_type_parameter: sess.features.borrow().default_type_params,
264                 enable_quotes: sess.features.borrow().quote,
265                 recursion_limit: sess.recursion_limit.get(),
266             };
267             let ret = syntax::ext::expand::expand_crate(&sess.parse_sess,
268                                               cfg,
269                                               macros,
270                                               syntax_exts,
271                                               krate);
272             if cfg!(windows) {
273                 os::setenv("PATH", _old_path);
274             }
275             ret
276         }
277     );
278
279     // JBC: make CFG processing part of expansion to avoid this problem:
280
281     // strip again, in case expansion added anything with a #[cfg].
282     krate = time(time_passes, "configuration 2", krate, |krate|
283                  syntax::config::strip_unconfigured_items(sess.diagnostic(), krate));
284
285     krate = time(time_passes, "maybe building test harness", krate, |krate|
286                  syntax::test::modify_for_testing(&sess.parse_sess,
287                                                   &sess.opts.cfg,
288                                                   krate,
289                                                   sess.diagnostic()));
290
291     krate = time(time_passes, "prelude injection", krate, |krate|
292                  syntax::std_inject::maybe_inject_prelude(krate));
293
294     time(time_passes, "checking that all macro invocations are gone", &krate, |krate|
295          syntax::ext::expand::check_for_macros(&sess.parse_sess, krate));
296
297     Some(krate)
298 }
299
300 pub fn assign_node_ids_and_map<'ast>(sess: &Session,
301                                      forest: &'ast mut ast_map::Forest)
302                                      -> ast_map::Map<'ast> {
303     struct NodeIdAssigner<'a> {
304         sess: &'a Session
305     }
306
307     impl<'a> ast_map::FoldOps for NodeIdAssigner<'a> {
308         fn new_id(&self, old_id: ast::NodeId) -> ast::NodeId {
309             assert_eq!(old_id, ast::DUMMY_NODE_ID);
310             self.sess.next_node_id()
311         }
312     }
313
314     let map = time(sess.time_passes(), "assigning node ids and indexing ast", forest, |forest|
315                    ast_map::map_crate(forest, NodeIdAssigner { sess: sess }));
316
317     if sess.opts.debugging_opts & config::AST_JSON != 0 {
318         let mut stdout = io::BufferedWriter::new(io::stdout());
319         let mut json = json::PrettyEncoder::new(&mut stdout);
320         // unwrapping so IoError isn't ignored
321         map.krate().encode(&mut json).unwrap();
322     }
323
324     map
325 }
326
327 /// Run the resolution, typechecking, region checking and other
328 /// miscellaneous analysis passes on the crate. Return various
329 /// structures carrying the results of the analysis.
330 pub fn phase_3_run_analysis_passes<'tcx>(sess: Session,
331                                          ast_map: ast_map::Map<'tcx>,
332                                          type_arena: &'tcx TypedArena<ty::TyS<'tcx>>,
333                                          name: String) -> ty::CrateAnalysis<'tcx> {
334     let time_passes = sess.time_passes();
335     let krate = ast_map.krate();
336
337     time(time_passes, "external crate/lib resolution", (), |_|
338          creader::read_crates(&sess, krate));
339
340     let lang_items = time(time_passes, "language item collection", (), |_|
341                           middle::lang_items::collect_language_items(krate, &sess));
342
343     let middle::resolve::CrateMap {
344         def_map,
345         freevars,
346         capture_mode_map,
347         exp_map2,
348         trait_map,
349         external_exports,
350         last_private_map
351     } =
352         time(time_passes, "resolution", (), |_|
353              middle::resolve::resolve_crate(&sess, &lang_items, krate));
354
355     // Discard MTWT tables that aren't required past resolution.
356     syntax::ext::mtwt::clear_tables();
357
358     let named_region_map = time(time_passes, "lifetime resolution", (),
359                                 |_| middle::resolve_lifetime::krate(&sess, krate, &def_map));
360
361     time(time_passes, "looking for entry point", (),
362          |_| middle::entry::find_entry_point(&sess, &ast_map));
363
364     sess.plugin_registrar_fn.set(
365         time(time_passes, "looking for plugin registrar", (), |_|
366             plugin::build::find_plugin_registrar(
367                 sess.diagnostic(), krate)));
368
369     let region_map = time(time_passes, "region resolution", (), |_|
370                           middle::region::resolve_crate(&sess, krate));
371
372     time(time_passes, "loop checking", (), |_|
373          middle::check_loop::check_crate(&sess, krate));
374
375     let stability_index = time(time_passes, "stability index", (), |_|
376                                stability::Index::build(krate));
377
378     time(time_passes, "static item recursion checking", (), |_|
379          middle::check_static_recursion::check_crate(&sess, krate, &def_map, &ast_map));
380
381     let ty_cx = ty::mk_ctxt(sess,
382                             type_arena,
383                             def_map,
384                             named_region_map,
385                             ast_map,
386                             freevars,
387                             capture_mode_map,
388                             region_map,
389                             lang_items,
390                             stability_index);
391
392     // passes are timed inside typeck
393     typeck::check_crate(&ty_cx, trait_map);
394
395     time(time_passes, "check static items", (), |_|
396          middle::check_static::check_crate(&ty_cx));
397
398     // These next two const passes can probably be merged
399     time(time_passes, "const marking", (), |_|
400          middle::const_eval::process_crate(&ty_cx));
401
402     time(time_passes, "const checking", (), |_|
403          middle::check_const::check_crate(&ty_cx));
404
405     let maps = (external_exports, last_private_map);
406     let (exported_items, public_items) =
407             time(time_passes, "privacy checking", maps, |(a, b)|
408                  middle::privacy::check_crate(&ty_cx, &exp_map2, a, b));
409
410     time(time_passes, "intrinsic checking", (), |_|
411          middle::intrinsicck::check_crate(&ty_cx));
412
413     time(time_passes, "effect checking", (), |_|
414          middle::effect::check_crate(&ty_cx));
415
416     time(time_passes, "match checking", (), |_|
417          middle::check_match::check_crate(&ty_cx));
418
419     time(time_passes, "liveness checking", (), |_|
420          middle::liveness::check_crate(&ty_cx));
421
422     time(time_passes, "borrow checking", (), |_|
423          middle::borrowck::check_crate(&ty_cx));
424
425     time(time_passes, "rvalue checking", (), |_|
426          middle::check_rvalues::check_crate(&ty_cx, krate));
427
428     // Avoid overwhelming user with errors if type checking failed.
429     // I'm not sure how helpful this is, to be honest, but it avoids a
430     // lot of annoying errors in the compile-fail tests (basically,
431     // lint warnings and so on -- kindck used to do this abort, but
432     // kindck is gone now). -nmatsakis
433     ty_cx.sess.abort_if_errors();
434
435     let reachable_map =
436         time(time_passes, "reachability checking", (), |_|
437              reachable::find_reachable(&ty_cx, &exported_items));
438
439     time(time_passes, "death checking", (), |_| {
440         middle::dead::check_crate(&ty_cx,
441                                   &exported_items,
442                                   &reachable_map)
443     });
444
445     time(time_passes, "lint checking", (), |_|
446          lint::check_crate(&ty_cx, &exported_items));
447
448     ty::CrateAnalysis {
449         exp_map2: exp_map2,
450         ty_cx: ty_cx,
451         exported_items: exported_items,
452         public_items: public_items,
453         reachable: reachable_map,
454         name: name,
455     }
456 }
457
458 pub fn phase_save_analysis(sess: &Session,
459                            krate: &ast::Crate,
460                            analysis: &ty::CrateAnalysis,
461                            odir: &Option<Path>) {
462     if (sess.opts.debugging_opts & config::SAVE_ANALYSIS) == 0 {
463         return;
464     }
465     time(sess.time_passes(), "save analysis", krate, |krate|
466          save::process_crate(sess, krate, analysis, odir));
467 }
468
469 /// Run the translation phase to LLVM, after which the AST and analysis can
470 /// be discarded.
471 pub fn phase_4_translate_to_llvm<'tcx>(analysis: ty::CrateAnalysis<'tcx>)
472                                        -> (ty::ctxt<'tcx>, trans::CrateTranslation) {
473     let time_passes = analysis.ty_cx.sess.time_passes();
474
475     time(time_passes, "resolving dependency formats", (), |_|
476          dependency_format::calculate(&analysis.ty_cx));
477
478     // Option dance to work around the lack of stack once closures.
479     time(time_passes, "translation", analysis, |analysis|
480          trans::trans_crate(analysis))
481 }
482
483 /// Run LLVM itself, producing a bitcode file, assembly file or object file
484 /// as a side effect.
485 pub fn phase_5_run_llvm_passes(sess: &Session,
486                                trans: &trans::CrateTranslation,
487                                outputs: &OutputFilenames) {
488     if sess.opts.cg.no_integrated_as {
489         let output_type = config::OutputTypeAssembly;
490
491         time(sess.time_passes(), "LLVM passes", (), |_|
492             write::run_passes(sess, trans, &[output_type], outputs));
493
494         write::run_assembler(sess, outputs);
495
496         // Remove assembly source, unless --save-temps was specified
497         if !sess.opts.cg.save_temps {
498             fs::unlink(&outputs.temp_path(config::OutputTypeAssembly)).unwrap();
499         }
500     } else {
501         time(sess.time_passes(), "LLVM passes", (), |_|
502             write::run_passes(sess,
503                               trans,
504                               sess.opts.output_types.as_slice(),
505                               outputs));
506     }
507
508     sess.abort_if_errors();
509 }
510
511 /// Run the linker on any artifacts that resulted from the LLVM run.
512 /// This should produce either a finished executable or library.
513 pub fn phase_6_link_output(sess: &Session,
514                            trans: &trans::CrateTranslation,
515                            outputs: &OutputFilenames) {
516     let old_path = os::getenv("PATH").unwrap_or_else(||String::new());
517     let mut new_path = sess.host_filesearch().get_tools_search_paths();
518     new_path.extend(os::split_paths(old_path.as_slice()).into_iter());
519     os::setenv("PATH", os::join_paths(new_path.as_slice()).unwrap());
520
521     time(sess.time_passes(), "linking", (), |_|
522          link::link_binary(sess,
523                            trans,
524                            outputs,
525                            trans.link.crate_name.as_slice()));
526
527     os::setenv("PATH", old_path);
528 }
529
530 pub fn stop_after_phase_3(sess: &Session) -> bool {
531    if sess.opts.no_trans {
532         debug!("invoked with --no-trans, returning early from compile_input");
533         return true;
534     }
535     return false;
536 }
537
538 pub fn stop_after_phase_1(sess: &Session) -> bool {
539     if sess.opts.parse_only {
540         debug!("invoked with --parse-only, returning early from compile_input");
541         return true;
542     }
543     if sess.show_span() {
544         return true;
545     }
546     return sess.opts.debugging_opts & config::AST_JSON_NOEXPAND != 0;
547 }
548
549 pub fn stop_after_phase_2(sess: &Session) -> bool {
550     if sess.opts.no_analysis {
551         debug!("invoked with --no-analysis, returning early from compile_input");
552         return true;
553     }
554     return sess.opts.debugging_opts & config::AST_JSON != 0;
555 }
556
557 pub fn stop_after_phase_5(sess: &Session) -> bool {
558     if !sess.opts.output_types.iter().any(|&i| i == config::OutputTypeExe) {
559         debug!("not building executable, returning early from compile_input");
560         return true;
561     }
562     return false;
563 }
564
565 fn escape_dep_filename(filename: &str) -> String {
566     // Apparently clang and gcc *only* escape spaces:
567     // http://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
568     filename.replace(" ", "\\ ")
569 }
570
571 fn write_out_deps(sess: &Session,
572                   input: &Input,
573                   outputs: &OutputFilenames,
574                   id: &str) {
575
576     let mut out_filenames = Vec::new();
577     for output_type in sess.opts.output_types.iter() {
578         let file = outputs.path(*output_type);
579         match *output_type {
580             config::OutputTypeExe => {
581                 for output in sess.crate_types.borrow().iter() {
582                     let p = link::filename_for_input(sess, *output,
583                                                      id, &file);
584                     out_filenames.push(p);
585                 }
586             }
587             _ => { out_filenames.push(file); }
588         }
589     }
590
591     // Write out dependency rules to the dep-info file if requested with
592     // --dep-info
593     let deps_filename = match sess.opts.write_dependency_info {
594         // Use filename from --dep-file argument if given
595         (true, Some(ref filename)) => filename.clone(),
596         // Use default filename: crate source filename with extension replaced
597         // by ".d"
598         (true, None) => match *input {
599             Input::File(..) => outputs.with_extension("d"),
600             Input::Str(..) => {
601                 sess.warn("can not write --dep-info without a filename \
602                            when compiling stdin.");
603                 return
604             },
605         },
606         _ => return,
607     };
608
609     let result = (|| -> io::IoResult<()> {
610         // Build a list of files used to compile the output and
611         // write Makefile-compatible dependency rules
612         let files: Vec<String> = sess.codemap().files.borrow()
613                                    .iter().filter(|fmap| fmap.is_real_file())
614                                    .map(|fmap| escape_dep_filename(fmap.name.as_slice()))
615                                    .collect();
616         let mut file = try!(io::File::create(&deps_filename));
617         for path in out_filenames.iter() {
618             try!(write!(&mut file as &mut Writer,
619                           "{}: {}\n\n", path.display(), files.connect(" ")));
620         }
621         Ok(())
622     })();
623
624     match result {
625         Ok(()) => {}
626         Err(e) => {
627             sess.fatal(format!("error writing dependencies to `{}`: {}",
628                                deps_filename.display(), e).as_slice());
629         }
630     }
631 }
632
633 pub fn collect_crate_types(session: &Session,
634                            attrs: &[ast::Attribute]) -> Vec<config::CrateType> {
635     // Unconditionally collect crate types from attributes to make them used
636     let attr_types: Vec<config::CrateType> = attrs.iter().filter_map(|a| {
637         if a.check_name("crate_type") {
638             match a.value_str() {
639                 Some(ref n) if *n == "rlib" => {
640                     Some(config::CrateTypeRlib)
641                 }
642                 Some(ref n) if *n == "dylib" => {
643                     Some(config::CrateTypeDylib)
644                 }
645                 Some(ref n) if *n == "lib" => {
646                     Some(config::default_lib_output())
647                 }
648                 Some(ref n) if *n == "staticlib" => {
649                     Some(config::CrateTypeStaticlib)
650                 }
651                 Some(ref n) if *n == "bin" => Some(config::CrateTypeExecutable),
652                 Some(_) => {
653                     session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
654                                      ast::CRATE_NODE_ID,
655                                      a.span,
656                                      "invalid `crate_type` \
657                                       value".to_string());
658                     None
659                 }
660                 _ => {
661                     session.add_lint(lint::builtin::UNKNOWN_CRATE_TYPES,
662                                      ast::CRATE_NODE_ID,
663                                      a.span,
664                                      "`crate_type` requires a \
665                                       value".to_string());
666                     None
667                 }
668             }
669         } else {
670             None
671         }
672     }).collect();
673
674     // If we're generating a test executable, then ignore all other output
675     // styles at all other locations
676     if session.opts.test {
677         return vec!(config::CrateTypeExecutable)
678     }
679
680     // Only check command line flags if present. If no types are specified by
681     // command line, then reuse the empty `base` Vec to hold the types that
682     // will be found in crate attributes.
683     let mut base = session.opts.crate_types.clone();
684     if base.len() == 0 {
685         base.extend(attr_types.into_iter());
686         if base.len() == 0 {
687             base.push(link::default_output_for_target(session));
688         }
689         base.sort();
690         base.dedup();
691     }
692
693     base.into_iter().filter(|crate_type| {
694         let res = !link::invalid_output_for_target(session, *crate_type);
695
696         if !res {
697             session.warn(format!("dropping unsupported crate type `{}` \
698                                    for target `{}`",
699                                  *crate_type, session.opts.target_triple).as_slice());
700         }
701
702         res
703     }).collect()
704 }
705
706 pub fn collect_crate_metadata(session: &Session,
707                               _attrs: &[ast::Attribute]) -> Vec<String> {
708     session.opts.cg.metadata.clone()
709 }
710
711 pub fn build_output_filenames(input: &Input,
712                               odir: &Option<Path>,
713                               ofile: &Option<Path>,
714                               attrs: &[ast::Attribute],
715                               sess: &Session)
716                            -> OutputFilenames {
717     match *ofile {
718         None => {
719             // "-" as input file will cause the parser to read from stdin so we
720             // have to make up a name
721             // We want to toss everything after the final '.'
722             let dirpath = match *odir {
723                 Some(ref d) => d.clone(),
724                 None => Path::new(".")
725             };
726
727             // If a crate name is present, we use it as the link name
728             let stem = sess.opts.crate_name.clone().or_else(|| {
729                 attr::find_crate_name(attrs).map(|n| n.get().to_string())
730             }).unwrap_or(input.filestem());
731
732             OutputFilenames {
733                 out_directory: dirpath,
734                 out_filestem: stem,
735                 single_output_file: None,
736                 extra: sess.opts.cg.extra_filename.clone(),
737             }
738         }
739
740         Some(ref out_file) => {
741             let ofile = if sess.opts.output_types.len() > 1 {
742                 sess.warn("ignoring specified output filename because multiple \
743                            outputs were requested");
744                 None
745             } else {
746                 Some(out_file.clone())
747             };
748             if *odir != None {
749                 sess.warn("ignoring --out-dir flag due to -o flag.");
750             }
751             OutputFilenames {
752                 out_directory: out_file.dir_path(),
753                 out_filestem: out_file.filestem_str().unwrap().to_string(),
754                 single_output_file: ofile,
755                 extra: sess.opts.cg.extra_filename.clone(),
756             }
757         }
758     }
759 }