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