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