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