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