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