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