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