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