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