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