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