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