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