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