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