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