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