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