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