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