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