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