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