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