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